zoukankan      html  css  js  c++  java
  • 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].

    思路:递推

    思路很明确,一层一层递推,并且只需要设立一个数组,本题不难。只需要注意一个解题公式即可

    代码:

    class Solution1 {
    public://for more information,please email:j.z.feng@foxmail.com
        vector<int> getRow(int rowIndex) {
            vector<int> result(1,1);
            if(rowIndex==0){
                return result;
            }
            
            for(int i=1;i<=rowIndex;i++){
                vector<int>temp=result;
                for(int j=1;j<=i-1;j++){
                    result[j]=temp[j]+temp[j-1];
                }
                result.push_back(1);
                temp.clear();
            }
            return result;
        }
    };

    class Solution2 {
    //此版本更加简洁
    public:<pre name="code" class="cpp">//for more information,please email:j.z.feng@foxmail.com
    vector<int> getRow(int rowIndex) { vector<int> result(rowIndex+1,1); if(rowIndex<=1){ return result; } for(int i=2;i<=rowIndex;i++){ for(int j=i-1;j>=1;j--){ result[j]=result[j]+result[j-1]; } } return result; }};
    
    

  • 相关阅读:
    递归函数底层原理浅析
    lambda expression & mutable
    命令mv
    printf的参数
    程序结构之静态本地变量
    汇编.align指令
    程序结构之全局变量
    命令touch
    更改gcc默认版本,实现gcc版本升降级
    命令chmod
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519910.html
Copyright © 2011-2022 走看看