学会思考
刻意练习
/*
Pascal's Triangle II
Description
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
*/

#include <stdlib.h>
#include <vector>
#include <iostream>

using namespace std;
vector<int> getRow(int rowIndex){
    vector<int> v(rowIndex + 1,0);
    v[0] = 1;
    for(int i = 0; i < rowIndex;i++){
        for(int j = i+1; j > 0; j--){
            v[j] += v[j-1];
        }
    }
    return v;
}

void printVector(vector<int> pt){
    cout << "{";
    for(int i = 0; i < pt.size(); i++){
        cout << pt[i] << ",";
    }

    cout << "}" << endl;
}

int main(int argc, char**argv)
{
    int n = 3;
    if(argc > 1){
        n = atoi(argv[1]);
    }
    printVector(getRow(n));
}

  

posted on 2020-03-06 15:16  Worty  阅读(126)  评论(0编辑  收藏  举报