LeetCode:pascals-triangle-ii

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuweiyuxiang/article/details/88059192

题目:
Given an index k, return the k th 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?
思路:
使用一个数组保存每行的值,从上到下,从右往左更新数组的值。
代码:
内层for循环从后往前更新数组的值,一次循环更新一个值。
外层的for循环,一次循环更新一行。

class Solution {
public:

	vector<int> getRow(int rowIndex) {
		vector<int> dp(rowIndex + 1, 1);

		for (int i = 2; i<rowIndex + 1; i++) {
			for (int j = i - 1; j>0; j--)
				dp[j] = dp[j] + dp[j - 1];
		}
		return dp;
	}
};

猜你喜欢

转载自blog.csdn.net/liuweiyuxiang/article/details/88059192