杨辉三角O(k)

https://leetcode-cn.com/problems/pascals-triangle-ii/submissions/

 

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 3
输出: [1,3,3,1]

 

问题思路:

1.刻画问题最优解的特征。     a[i][j] = a[i-1][j-1] + a[i-1][j]

2.递归、遍历求解最优解。  (归纳遍历求解形式) 

3.自底向上或自顶向下求解最优解。 

 

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ans = {1};
        for(int i=1; i<=rowIndex; i++){
            vector<int> temp = {1};
            for(int j=1; j<i; j++){
                temp.push_back(ans[j-1]+ans[j]);
            }
            temp.push_back(1);
            ans = temp;
        }

        return ans;
    }
};

 

posted @ 2021-07-01 21:51  会飞的雅蠛蝶  阅读(153)  评论(0编辑  收藏  举报