zoukankan      html  css  js  c++  java
  • 杨辉三角

    Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


    In Pascal's triangle, each number is the sum of the two numbers directly above it.

    Example:

    Input: 5
    Output:
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    
     题意:对给定的非负整数numRows,生成杨辉三角的前numRows行,杨辉三角第n行(从1开始)有n个元素,每一行的第一个和最后一个为1,其它的数是它左上方右上方数字的和。
    思路:从第一行开始,逐行地生成杨辉三角的每一行,在每一行中,首位元素设置为1,其它的元素设置为正上方,和左上方元素的和
    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> res;
            if(numRows==0) return res;  
            for(int i=0;i<numRows;i++){
                vector<int> temp(i+1,0);
                for(int j=0;j<=i;j++){
                    if(j==0 || j==i) temp[j]=1;
                    else temp[j]=res[i-1][j-1]+res[i-1][j];
                }
                res.push_back(temp);
            }
            return res;
        }
    };

    这里的每一行元素我又开了一个临时数组,其实直接用保存结果的二维数组的第i行就好了,下面的是参考了https://www.cnblogs.com/grandyang/p/4031536.html,额其实好像是直接把代码拿来用了,,,

    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> res;
            if(numRows==0) return res; 
            res.assign(numRows, vector<int>(1));
            for(int i=0;i<numRows;i++){
                res[i][0]=1;
                if(i==0) continue;
                for(int j=1;j<i;j++){
                    res[i].push_back(res[i-1][j-1]+res[i-1][j]);
                }
                res[i].push_back(1);
            }
            return res;
        }
    };
  • 相关阅读:
    [算法] Tarjan算法求割点
    [题解] POJ2689 [质数距离]
    [题解] 「NOIP2009」最优贸易
    pyCharm更换主题、字体大小和编辑器字体颜色
    python之冒泡排序简单算法
    修改pip阿里镜像
    Postman工具简介
    接口文档解析
    HTTP接口请求
    接口(API)测试学习
  • 原文地址:https://www.cnblogs.com/Bipolard/p/9993079.html
Copyright © 2011-2022 走看看