[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?


來源:https://oj.leetcode.com/problems/pascals-triangle-ii/


思路:

楊輝三角的應用,和之前的類似

C++ AC代碼:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> tmp, result; 
        
		if(rowIndex < 0)
            return result;
       
        result.push_back(1);
		
        for(int i=1;i<=rowIndex;i++)
        {
            tmp.push_back(1);           //每行的頭數字
            
            for(int j=1;j<i;j++)
                tmp.push_back(result[j-1] + result[j]);   //每行中間的數字
            
            tmp.push_back(1);         //每行的尾數字
			result = tmp;
			tmp.clear();
        }
        return result;		
    }
};

運行時間 4ms

另一種網上的方法:
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> myvector, tmpvector; 
        if(rowIndex<0)  
            return myvector;  
        myvector.push_back(1);  
        for(int i=1;i<=rowIndex;i++)  
        {   
            tmpvector.push_back(1);  
            for(int j=1;j<i;j++)  
                tmpvector.push_back(myvector[j-1]+myvector[j]);  
            tmpvector.push_back(1);  
            myvector = tmpvector;  
            tmpvector.clear();  
        }                 
        return myvector;  
    }
};

運行時間28ms


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