Pascal's Triangle II
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?
思路:
最开始的想法是用两个vector依次记录当前行和上一行的结果。但是要求用k的空间,所以使用一个vector,每次从后往前r[j] = r[j] + r[j-1]即可。
代码:
1 vector<int> getRow(int rowIndex) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 vector<int> result(rowIndex+1,0); 5 result[0] = 1; 6 int i, j; 7 for(i = 1; i <= rowIndex; i++){ 8 for(j = i; j > 0; j--){ 9 result[j] = result[j] + result[j-1]; 10 } 11 } 12 return result; 13 }