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?
给定行索引k, k从0开始,返回该索引指向的杨辉三角的行
class Solution { public: vector<int> getRow(int rowIndex) { vector<int>result; if(rowIndex<0)return result; //维护两个rowIndex+1长度的数组, rowIndex为偶数时,行元素存储在row1中;rowIndex为奇数时,行元素存储在row2中 vector<int> row1(rowIndex+1, 1); vector<int> row2(rowIndex+1, 1); int indexCount=0; //当前已经生成的行的行索引 while(indexCount<rowIndex){ indexCount++; if(indexCount%2==0){ //当前要从row2生成下一行元素,存到row1中 //row2有indexCount个元素,row1中有indexCount+1个元素 for(int i=1; i<indexCount; i++){ row1[i]=row2[i-1]+row2[i]; } } else{ //当前要从row1生成下一行元素,存到row2中 //row1有indexCount个元素,row2中有indexCount+1个元素 for(int i=1; i<indexCount; i++){ row2[i]=row1[i-1]+row1[i]; } } } //如果rowIndex是偶数,返回row1,否则返回row2 if(rowIndex%2==0)return row1; else return row2; } };
LeetCode: Pascal's Triangle II [119],布布扣,bubuko.com
LeetCode: Pascal's Triangle II [119]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/28850023