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?

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

vector<int> pacal2(int n);
int main()
{
	int a[] = { 2, 4, 6, 8, 9 };
	vector<int> temp;
	for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++)
	{
		temp = pacal2(a[i]);
		for (int data : temp)
			cout << data << " " << endl;
		temp.clear();
	}
}

vector<int> pacal2(int n)
{
	vector<int> result(n + 1, 0);
	for (int i = 0; i <= n; i++)  //表示第i行的赋值
	{
		if (i == 0)
		{
			result[0] = 1;
			continue;
		}
		for (int j = n; j >= 1; j--) //第i行中每个元素的值 第i行的数值是第i-1行中同列上一列的和的值
			//100000000000
			//110000000000
			//121000000000
			//133100000000
			//146410000000  数组中元素变化的形式  
			//不能从前面进行遍历,从前往后遍历容易导致调用改变的值 数组一般改变值得从后往前遍历
		{
			result[j] = result[j] + result[j - 1];
		}
	}
}


class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> v;
        if(rowIndex < 0) return v;
        for(int i = 0; i <= rowIndex; ++i){
            v.push_back(0);
        }
        for(int j = 0; j <= rowIndex; ++j){
            v[rowIndex] = 1;
            for(int k = rowIndex-1; k > 0; --k){
                v[k] = v[k] + v[k-1];
            }
            v[0] = 1;
        }
        return v;
    }
};


你可能感兴趣的:(Pascal's Triangle II)