首页 > 代码库 > leetcode 119

leetcode 119

119. 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?

输出Pascal三角形的第k行(从0开始);空间复杂度为O(k);

从第0行开始生成,每次利用已经生成的行,在原有空间上生成下一行,直到生成所要求的行。

代码入下:

 1 class Solution { 2 public: 3     vector<int> getRow(int rowIndex) { 4         vector<int>  pascal; 5         pascal.push_back(1); 6         int m = 1; 7         for(int i = 0; i <= rowIndex; i++) 8         { 9             if(rowIndex == 0)10             {11                 return pascal;12             }13             for(int j = 1; j < i+1; j++)14             {15                 if(j == i)16                 {17                     pascal.push_back(1);18                     break;19                 }20                 int n = pascal[j];21                 pascal[j] = m + n;22                 m = n;23             }24         }25        return pascal;26     }27 };

 

leetcode 119