zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    第13讲——使用类
    第12讲——对象和类
    第11讲——面向对象编程
    第10讲——名称空间
    数论19——高斯消元
    贪心思想
    重要的转变(感觉自己最近堕落必读)
    java面试
    Java泛型
    系统设计
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3802917.html
Copyright © 2011-2022 走看看