Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector< vector<int> > r;
vector<int> a,b;
if(numRows >= 1) {
a.push_back(1);
r.push_back(a);
}
for(int j = 2; j <= numRows; j++) {
b.clear();
b.push_back(1);
for(int i = 1; i <= j - 2; i++) {
b.push_back(a[i]+a[i-1]);
}
b.push_back(1);
r.push_back(b);
a = b;
}
return r;
}
};
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?
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> a,b;
b.push_back(1);
a = b;
for(int j = 1; j <= rowIndex; j++) {
b.clear();
b.push_back(1);
for(int i = 1; i <= j - 1; i++) {
b.push_back(a[i]+a[i-1]);
}
b.push_back(1);
a = b;
}
return b;
}
};
思路:求解第n行,可以用数学中的牛顿二项式公式,用组合数C(n,k)计算每一项。但因为组合数涉及乘除,数字会很巨大,为防止溢出需要使用long long类型,且因为大数乘除,速度比只用加减法慢。
解法只使用加减,看起来麻烦(计算了k前面的所有行),实际上速度快了很多,就是因为没有使用乘除法。
题目中要求空间复杂度 O(k),这是很容易达到的。只有仍然使用 Pascal;s Triangle 的解法才能达到 O(k^2)的空间复杂度。
解法使用大约了 2 * k * sizeof(int) 的存储空间,还有优化可能,可以优化成 k * sizeof(int) 的解法,虽然同是 O(k)。
附小小优化后的解法:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> b(rowIndex + 1);
b[0] = 1;
for(int i = 0; i <= rowIndex ; i++) {
for (int j = i; j > 0; j--) {
b[j] = b[j] + b[j-1];
}
}
return b;
}
};