Pascal's Triangle II

 

Q: Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note: extra space: O(K)

A: 开辟k+1大的空间用于存储结果。做K+1次迭代。第i次迭代,将result[i]置成1,同时对于j:[1,i-1],result[j] = result[j] + old result[j-1];

    vector<int> getRow(int rowIndex) {
    // Start typing your C/C++ solution below
	// DO NOT write int main() function
	vector<int> result;

	if(rowIndex<0)
		return result;

	result.resize(rowIndex+1);
	
	int oldvalue,temp;
	for(int i=0;i<=rowIndex;i++)
	{
		result[i] = 1;
		oldvalue = result[0];
		for(int j=1;j<i;j++)
		{
			temp = result[j];
			result[j] = oldvalue + result[j];
			oldvalue = temp;
		}
	}

	return result;
}

  

posted @ 2013-06-13 21:57  summer_zhou  阅读(142)  评论(0)    收藏  举报