zoukankan      html  css  js  c++  java
  • [leetcode.com]算法题目

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

     1 class Solution {
     2 public:
     3     vector<vector<int> > generate(int numRows) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if(0 == numRows){
     7             vector<vector<int> > result;
     8             return result;
     9         } 
    10              
    11         vector<vector<int> > result(numRows);
    12         
    13         vector<int> first(1,1);
    14         result[0] = first;
    15         for(int i=1;i<numRows;i++){
    16             result[i] = nextTriangle(result[i-1]);
    17         }
    18         
    19         return result;    
    20     }
    21     
    22     vector<int> nextTriangle(vector<int> a){
    23         int k = a.size();
    24         vector<int> next(k+1);
    25         for(int i=0;i<k+1;i++){
    26             if(0==i){
    27                 next[i] = a[i];
    28                 continue;
    29             }
    30             if(k==i){
    31                 next[i] = a[k-1];
    32                 continue;
    33             }
    34             next[i] = a[i-1]+a[i];
    35         }
    36         return next;
    37     }
    38 };
    我的答案

    思路:创建一个函数,使用上一行的vector去计算下一行的vector,然后反复调用即可。需要尤其注意输入的值为0时候的情况。

  • 相关阅读:
    使用语句修改数据表结构
    C# 写日志到文件
    mysql 语句要求
    跨discuz站获取
    php 记录图片浏览次数次数
    js获取url传递参数值
    jquery.validate.js 验证表单时,在IE当中未验证就直接提交的原因
    mkfs
    mount
    dd
  • 原文地址:https://www.cnblogs.com/xuning/p/3317762.html
Copyright © 2011-2022 走看看