119. Pascal's Triangle II (Graph; WFS)

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

 
思路:从右往左遍历并填写三角形的图结构 
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> a(rowIndex + 1);
        
        a[0] = 1;
        for(int i = 1; i <= rowIndex; i++) //遍历行
            for(int j = i; j >= 0; j--) //遍历行中的元素,第k行有k个元素。注意行中元素需要从右往左遍历,否则下一行填写的结果会覆盖上一行还未使用的元素
                if (j == i)
                    a[j] = a[j-1];
                else if (j == 0)
                    a[j] = a[j];
                else
                    a[j] = a[j-1] + a[j];
                    
        return a;                    
    }
};

 

posted on 2015-10-04 15:43  joannae  阅读(134)  评论(0编辑  收藏  举报

导航