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

  • 相关阅读:
    Java入门
    Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8
    pypy3.8安装
    asyncio执行阻塞代码
    linux安装go
    python消费rabbitmq
    绑定进程到指定cpu运行
    负载均衡算法
    django版本规划
    FastAPI WebSocket 简单演示
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519910.html
Copyright © 2020-2023  润新知