119. Pascal's Triangle II

119. 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].
Analysis:
118. Pascal’s Triangle 的进阶。本来想用定理“第n行的第k個數字為組合數C{n}^{k},(n,k从0起)”直接算,发现这样算会出现数很大的情况,所以还是只能一层一层的算。
所以跟上一题基本一样,只是算法空间复杂度更小了。
Source Code(C++):

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

/******************************根据定理:第n行的第k個數字為組合數C{n}^{k},(n,k从0起算),这种方法容易导致数溢出*************************************/
/* class Solution { public: vector<int> getRow(int rowIndex) { vector<int> v; if (rowIndex == 0) { v.push_back(1); } else if (rowIndex == 1) { v.push_back(1); v.push_back(1); } else { v.push_back(1); for (int k=1; k<rowIndex; k++) { long long int k_factorial=1; long long int permutation=1; for (int j=rowIndex-k+1; j<=rowIndex; j++) { permutation *= j; } for (int i=1; i<=k; i++) { k_factorial *= i; } v.push_back(permutation/k_factorial); } v.push_back(1); } return v; } }; */
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> v;
        if (rowIndex == 0) {
            v.push_back(1);
        }
        else if (rowIndex == 1) {
            v.push_back(1);
            v.push_back(1);
        }
        else {
            v.push_back(1);
            v.push_back(1);
            for (int i=2; i<=rowIndex; i++) {
                for (int j=0; j<v.size()-1; j++)
                {
                    v.at(j) += v.at(j+1);
                }
                v.insert(v.begin(), 1);
            }
        }
        return v;
    }
};

int main() {
    Solution sol;
    vector<int> v;
    v = sol.getRow(3);
    for (int i=0; i<v.size(); i++) {
        cout << v.at(i);
    }
    return 0;
}

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