1354. Pascal's Triangle II

描述

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

1.Note that the row index starts from 0.
2.In Pascal's triangle, each number is the sum of the two numbers directly above it.

您在真实的面试中是否遇到过这个题?  

样例

Example:

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

挑战

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

只用O(K)的空间,迭代递推进行计算即可。

class Solution {
public:
    /**
     * @param rowIndex: a non-negative index
     * @return: the kth index row of the Pascal's triangle
     */
    vector<int> getRow(int rowIndex) {
        // write your code here
        vector<int> vec(rowIndex+1);
        vec[0] = 1;       
        for (int i=0; i<=rowIndex; i++) {
            for (int j=i; j>0; j--) {     
                vec[j] = vec[j] + vec[j-1];
            }
        }
        return vec;
    }
};


猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80718554