[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)的空间,那么就直接初始化,然后按照Pascal's Triangle的规律,计算。
由于覆盖的问题,从后往前计算就可以避免。
1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 vector<int> result(rowIndex+1,1); 5 for(int i=0;i<=rowIndex;i++) 6 { 7 for(int j=i-1;j>0;j--) 8 { 9 result[j] = result[j-1]+result[j]; 10 } 11 } 12 return result; 13 } 14 };