[Leetcode] pascals triangle ii 帕斯卡三角

Given an index k, return the k th 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?

 题意:给定整数K,返回行下标为K的数组。

思路:  关键点是,每次遍历数组时都是从后往前遍历,因为从前往后遍历,没有办法保存之前所得到的信息。若从前往后遍历,当K=3时,第三行为1,2,1 ,第四行为1,3,4,1 ,而从后往前遍历则为1,3,3,1 。代码如下:

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) 
 4     {
 5         if(rowIndex<0)    return {};
 6         
 7         vector<int> res(rowIndex+1,0);  
 8         res[0]=1;
 9 
10         for(int i=0;i<=rowIndex;++i)
11         {
12             for(int j=i;j>0;j--)
13             {
14                 res[j]=res[j]+res[j-1];
15             }
16         }    
17         return res;    
18     }
19 };

 注:类似dp的滚动数组。

原文地址:https://www.cnblogs.com/love-yh/p/7211989.html