您的位置:首页 > 其它

LEETCODE--Pascal's Triangle II

2015-11-12 10:27 288 查看
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?

Subscribe to see which companies asked this question

方法一:

从后往前进行加法赋值;

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> A;
A.push_back(1);
if(rowIndex == 0)
return A;
A.push_back(1);
if(rowIndex == 1)
return A;
for(int x = 2; x <= rowIndex; x++){
A.push_back(0);
}
for(int i = 2; i <= rowIndex; i++){
A[i] = 1;
for(int j = i-1; j > 0; j--){
A[j] = A[j] + A[j-1];
}
A[0] = 1;
}
return A;
}
};


方法二:

class Solution {
public:
vector<int> getRow(int rowIndex) {

vector<vector<int>> finsh;
vector<int> last;
vector<int> add;
finsh.push_back(add);
finsh[0].push_back(1);
rowIndex += 1;
if(rowIndex == 1)
return finsh[0];
else{
for(int i = 1; i < rowIndex; i++){
if(i == finsh.size())
{
vector<int> add;
finsh.push_back(add);
}
finsh[i].push_back(1);
for(int j = 1; j <= i; j++){
if(finsh[i].size() == i)
finsh[i].push_back(1);
else{
int x = finsh[i-1][j-1];
int y = finsh[i-1][j];
int elem = x + y;
finsh[i].push_back(elem);
}
}
}
return finsh[rowIndex-1];
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: