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?
本题在LeetCode Pascal’s Triangle的基础上,要求只用O(k)空间复杂度,输出杨辉三角的第k行结果。
关键在于只能用O(k)的空间。我们要算第k行的结果,只要知道第k-1行结果就可以了,所以可以用O(k)的空间保留前一行的结果。每计算到一行就交换一下ans和tmp,完整代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex)
{
vector<int> ans(rowIndex + 1, 1), tmp(rowIndex + 1, 1);
if (rowIndex == 0 || rowIndex == 1)
return ans;
for (int row = 2; row <= rowIndex; row++) {
for (int col = 1; col < row; col++) {
tmp[col] = ans[col – 1] + ans[col];
}
swap(ans, tmp);
}
return ans;
}
};
本代码提交AC,用时0MS。
其实这题不需要tmp数组也行,就是每行算的时候从后往前算,因为ans[col]只会用到ans[col]和ans[col-1],所以从后往前填数组,即使覆盖了之前的结果,也对前面的计算没有影响。
这种思路在DP解背包问题中很常见,完整代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex)
{
vector<int> ans(rowIndex + 1, 1);
if (rowIndex == 0 || rowIndex == 1)
return ans;
for (int row = 2; row <= rowIndex; row++) {
for (int col = row – 1; col > 0; col–) {
ans[col] += ans[col – 1];
}
}
return ans;
}
};
本代码提交AC,用时0MS。
Pingback: LeetCode Triangle | bitJoy > code