119. Pascal's Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
方法1:
思路:
用一个current来保持前面一行,但是还可以再优化。如果从后往前更新
class Solution {
public:
vector<int> getRow(int rowIndex) {
if (rowIndex == 0) return {1};
vector<int> current = {};
vector<int> result;
for (int i = 0; i <= rowIndex; i++){
result.resize(i + 1, 1);
for (int k = 1; k < i; k++){
result[k] = current[k - 1] + current[k];
}
current = result;
}
return result;
}
};
grandyang: http://www.cnblogs.com/grandyang/p/4031536.html
举个栗子:
numRows = 5
result = {1, 0, 0, 0, 0, 0}
i = 1
j = 1
result = {1, 1, 0, 0, 0, 0}
#######################
i = 2
j = 2
result = {1, 1, 1, 0, 0, 0}
i = 2
j = 1
result = {1, 2, 1, 0, 0, 0}
#######################
i = 3
j = 3
result = {1, 2, 1, 1, 0, 0}
i = 3
j = 2
result = {1, 2, 3, 1, 0, 0}
i = 3
j = 1
result = {1, 3, 3, 1, 0, 0}
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1);
res[0] = 1;
for (int i = 1; i <= rowIndex; ++i) {
for (int j = i; j >= 1; --j) {
res[j] += res[j - 1];
}
}
return res;
}
};