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?
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 || 119、Pascal's Triangle II
原文地址:http://blog.csdn.net/hustyangju/article/details/45243829