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

利用队列实现

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;
}

 

posted @ 2014-06-22 20:28  OpenSoucre  阅读(505)  评论(0编辑  收藏  举报