zoukankan      html  css  js  c++  java
  • 杨辉三角(数组)

    //杨辉三角(数组)
    /*
    * @Description: Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
     * Input: 5
     * Output:
     * [
     *      [1],
     *     [1,1],
     *    [1,2,1],
     *   [1,3,3,1],
     *  [1,4,6,4,1]
     * ]
    */
    #include <stdlib.h>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    vector<vector<int>> generate(int numRows){
        vector<vector<int>> pascalTriangle;
        for(int i = 0; i < numRows; i++){
           vector<int> v;
           if(i == 0){
               v.push_back(1);
           }
           else{
               v.push_back(1);
               for(int j=0; j < pascalTriangle[i-1].size()-1;j++){
                   v.push_back(pascalTriangle[i-1][j] + pascalTriangle[i-1][j+1]);
               }
               v.push_back(1);
           }
           pascalTriangle.push_back(v);
        }
        return pascalTriangle;
    }
    
    void printTriangle(vector<vector<int>> pt){
        cout << "[" << endl;
        for(int i = 0;i<pt.size();i++){
            for(int space=(pt.size()-i-1);space>=0;space--){
                cout << " ";
            }
            for(int j = 0; j < pt[i].size(); j++){
                cout << pt[i][j];
                if(j<pt[i].size()-1){
                    cout << ",";
                }
            }
    
            cout << "]";
            if(i<pt.size()-1){
                cout << ",";
            }
            cout << endl;
        }
        cout <<  "]" << endl;
    }
    
    int main(int argc, char**argv)
    {
        int n = 3;
        if(argc > 1){
            n = atoi(argv[1]);
        }
        printTriangle(generate(n));
    }
    

      

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    Diffusion Particle Resolver
    GPU Jacobi Iterator
    Remark for ColorSpectrum Rendering
    关于Windows的命令行多语言输出
    DPR Sphere in Cloud
    看到一篇有意思的东西,记录一下
    GFS的系统架构
    jsp实现树状结构
    工作笔记
    批量删除
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12426376.html
Copyright © 2011-2022 走看看