iven 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?
要求只能用O(k)空间,所以用(rowIndex+1)*2的数组来存储结果,每次交换cur和pre。
状态转换方程dp[cur][i] = dp[pre][i-1] + dp[pre][i];
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector< vector< int> > dp( 2, vector< int>( rowIndex+1, 0));
int cur = 1;
int pre = 0;
dp[pre][0] = 1;
dp[cur][0] = 1;
int n = 1;
while( n <= rowIndex){
for( int i = 1; i < n + 1; ++i){
dp[cur][i] = dp[pre][i-1] + dp[pre][i];
}
++n;
cur = !cur;
pre = !pre;
}
return dp[pre];
}
};