您的位置:首页 > 其它

[Leetcode 36] 119 Pascal's Triangle II

2013-05-24 06:27 169 查看
Problem:

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?

Analysis:

The direct way to solve the problem is to use the formula: C(i, k) = k! / (i! * (k-i)!). But it will exceed the int number range if k is very large.

So we have to use the iterative way to construct the answer: to compute kth row, we first compute (k-1)th row and then use it to construct the desired row.

Code:

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

res.push_back(1);
if (rowIndex == 0) return res;
res.push_back(1);
if (rowIndex == 1) return res;

for (int i=1; i<rowIndex; i++) {
vector<int> tmp;
tmp.push_back(1);
for (int j = 1; j <= i; j++) {
tmp.push_back(res[j-1] + res[j]);
}
tmp.push_back(1);

res = tmp;
}

return res;
}

};


View Code

Attention:

Notice to add a new element into tmp, use push_back, not [].

The inner loop's max value is i not rowIndex.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: