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

  • 相关阅读:
    面向对象 小游戏 打飞机
    面向对象2
    面向对象
    正则 校验邮箱
    正则 过滤敏感字
    Strobogrammatic Number
    Binary Tree Right Side View
    [?]*Closest Binary Search Tree Value II
    *Closest Binary Search Tree Value
    *Inorder Successor in BST
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519910.html
Copyright © 2011-2022 走看看