leetcode || 119、Pascal's Triangle II

problem:

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?

Hide Tags
  Array
题意:输出杨辉三角形的第K层 即:第K+1行

thinking:

题目要求使用O(K)的额外空间,开一个K+1大小的数组,对于产生一个新的行用从后往前的方法来更新,这样就只需一个O(k)的空间

code:

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--)
                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;                    
    }
};


你可能感兴趣的:(LeetCode,pascal,杨辉三角)