12
05/2015
[LeetCode] Pascal's Triangle II
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?
解题思路:
题目要求空间复杂度为O(k),我们只需记录上一层的记录即可。这里的k从0开始计数。
class Solution { public: vector<int> getRow(int rowIndex) { if(rowIndex<0){ return vector<int>(); } vector<int> result; result.push_back(1); for(int i = 1; i< rowIndex + 1; i++){ //第i行 vector<int> lastRow = result; result.resize(i+1); for(int j=0; j<i+1; j++){ //第i行第j个数 if(j==0||j==i){ result[j]=1; }else{ result[j] = lastRow[j-1]+lastRow[j]; } } } return result; } };
二次刷题(2015-08-04)
我们可以直接在原地进行替换。只需要缓存一个数即可
class Solution { public: vector<int> getRow(int rowIndex) { if(rowIndex<0){ return vector<int>(); } vector<int> result(rowIndex + 1); result[0] = 1; for(int i=1; i<=rowIndex; i++){ int cache = result[0]; for(int j=1; j<i; j++){ int temp = result[j]; result[j] += cache; cache = temp; } result[i] = 1; } return result; } };
转载请注明:康瑞部落 » [LeetCode] Pascal's Triangle II
0 条评论