[Leetcode] Pascal's Triangle II

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?

Subscribe to see which companies asked this question

這個問題要求儲存空間要小,可以採用遞歸的方法去處理

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> cur(rowIndex+1,1);
        if(rowIndex == 0){
            return cur;
        }
        vector<int> last=getRow(rowIndex-1);
        for(int i = 0;i<cur.size();i++){
            if(i != 0 && i != cur.size()-1) {
                cur[i]=last[i]+last[i-1];
            }
        }
        return cur;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章