leetcode Pascal's Triangle II

OpenSoucre發表於2014-06-22

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?

利用佇列實現

vector<int> getRow(int index){
    index++;
    vector<int> res;
    if(index == 0) return res;
    if(index == 1) {res.push_back(1);return res;}
    if(index == 2) {res.push_back(1);res.push_back(1);return res;}
    queue<int> que;
    que.push(1);que.push(1);
    int cnt = 2, i = 0;
    while(!que.empty() && cnt  < index ){
        int a = que.front();que.pop();
        if(i == 0) que.push(1);
        que.push(a+que.front());
        i++;    
        if(i == cnt-1){que.pop();que.push(1);cnt++;i=0;}
    }
    while(!que.empty()) {res.push_back(que.front());que.pop();}
    return res;
}
佇列實現

 直接利用陣列實現,注意新行數值的改變要從後面進行,不然會覆蓋先前陣列的值

做完這題,可以看一下從前面往後面計算的題Leetcode Triangle

vector<int> getRow(int index){
    vector<int> res(++index,1);
    for(int i = 3; i < index+1; ++ i){
        for(int j = i-2;j >=1; -- j){
            res[j] +=res[j-1];
        }
    }
    return res;
}

 

相關文章