LeetCode 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?


与上一题相似,不过只是求特定的某一层,要求只用线性的空间。

第k层的数依次为c(n,0),c(n,1),c(n,2)...c(n,n),

而c(n,i)的递推公式为c(n,i)=c(n,i-1)*(n-i+1)/i,首项c(n,0)为1。

由此递推即可。


代码:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ret(1,1);
		long long temp=1;	//每个要压入的数
		for(int i=1;i<=rowIndex;i++)	//递推
		{
			temp=temp*(rowIndex-i+1)/i;
			ret.push_back(temp);
		}
		return ret;
    }
};





你可能感兴趣的:(LeetCode,C++,算法)