leetcode Pascal's Triangle II

Pascal's Triangle II

  Total Accepted: 16710  Total Submissions: 54790 My Submissions

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?

Have you been asked this question in an interview?  Yes

Discuss


1.按照规律把数字填写下来,除了第一行意外,其余的第k行有k+1个数字。

2.用两个k+1大的array,相互进行累加和替换,得出最终结果。

//10:05
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> dp1(rowIndex+1,0);
        vector<int> dp2(rowIndex+1,0);
        int i,j;
        dp1[0] = 1;
        for(i=1;i<=rowIndex;i++)
        {
            for(j=0;j<=i;j++)
            {
                if(j==0)
                {
                    dp2[j] = dp1[j];
                }else if(j==i)
                {
                    dp2[j] = dp1[j-1];
                }else
                {
                    dp2[j] = dp1[j-1] + dp1[j];
                }
            } // write the value in the previous array
            for(j=0;j<=i;j++)
            {
                dp1[j] = dp2[j];
            }
        }
        return dp1;
    }
};


你可能感兴趣的:(LeetCode,递推)