119. Pascal's Triangle II (Array)

##### 题目描述:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

Example:

Input: 3
Output: [1,3,3,1]

##### 分析:

根据题目的动图可以发现下一层第i个元素等于上一层第i个元素和i+1个元素之和。因此可以通过逐层计算可以得到结果。

 public List<Integer> getRow(int rowIndex) {
        List<Integer> last = new ArrayList<Integer>();
        for(int i=0;i<rowIndex+1;i++){
            List<Integer> curr = new ArrayList<Integer>();
            for(int j=0;j<=i;j++){
                if(j==0 || j==i)
                    curr.add(1);
                else
                    curr.add(last.get(j)+last.get(j-1));
            }
            last=curr;
        }
        return last;
    }

###### 方法二:

不用多余的空间也可以的。每次向list中加入1,然后从倒数第二个元素向前第I个元素等于第i个元素加上第i-1个元素,直到第一个元素(是1).

 public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<Integer>(rowIndex+1);
        for(int i=0;i<rowIndex+1;i++){
            res.add(1);
            for(int j=i-1;j>0;j--){//注意j的初值(最后一个和第一个元素是1)
                res.set(j,res.get(j)+res.get(j-1));
            }
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/85641793
今日推荐