2014年5月8日星期四

Loop Solution - Pascal's Triangle II

The idea is to find the rules between numbers inside the array for kth… (int)((long) res.get(curInsertPos - 1) * (long) (rowIndex + 1 - curInsertPos) / (long) curInsertPos);

Another tricky part is the condition to exit the loop… which I use the amount of current index… and check if there is only one capacity allowed!


public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        // if(rowIndex == 0){
        //     res.add(1);
        //     return res;
        // }
        // res.add(1);
        // res.add(1);
        // int countIndex = res.size();
        // int curInsertPos = 1;
        // int preNum = 1;
        // int loop = 1;
        // while(countIndex < rowIndex + 1){
        //     int insertNum = (int)((long)preNum * (long)(rowIndex + 1 - loop) / (long)loop);
        //     if(rowIndex + 1 - countIndex == 1){
        //         res.add(curInsertPos, insertNum);
        //         countIndex++;
        //     }else{
        //         res.add(curInsertPos, insertNum);
        //         res.add(curInsertPos + 1, insertNum);
        //         countIndex += 2;
        //     }
        //     curInsertPos++;
        //     preNum = insertNum;
        //     loop++;
        // }
       
        int count = 0;
        int curInsertPos = 0;
        while(count <= rowIndex){
            int insertNum = 1;
            if(curInsertPos > 0){
                insertNum = (int)((long) res.get(curInsertPos - 1) * (long) (rowIndex + 1 - curInsertPos) / (long) curInsertPos);
            }
            if(rowIndex == count){
                res.add(curInsertPos, insertNum);
                count++;
            }else{
                res.add(curInsertPos, insertNum);
                res.add(++curInsertPos, insertNum);
                count += 2;
            }
        }
       
        return res;
    }
}

没有评论: