zoukankan      html  css  js  c++  java
  • leetcode 118 Pascal's triangle.

    < 不得不吐槽一句,博客园的体验真的不如印象笔记,图片缩小太不方便阿而且界面乱而且丑>

    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开始,可以方便些,然后
    • 忘记了vector.push_back() 的第一个元素是0开始的
    • 记得处理0的情况
    • 还有数组处理时 ,不可以用未分配的 

    class Solution
    {
    public:
    vector<vector<int> > generate(int numRows)
    {

    vector<vector<int> >result;
    if (numRows == 0) return result;

    vector<int> v;
    v.push_back(1);// 不可用 result[0][0] = 1;
    result.push_back(v);
    if (numRows == 1) return result;

    for(int i = 1; i < numRows; i++)
    {
    vector<int> rows;
    rows.push_back(1);
    for (int j=1; j<i; j++)
    {
    rows.push_back(result[i-1][j] + result[i-1][j-1]); // 不可使用 result[i][j] 非法使用
    }
    rows.push_back(1);
    result.push_back(rows);
    rows.clear();
    }
    return result;
    }
    };

    单元测试没写

     
  • 相关阅读:
    Single Number II
    Pascal's Triangle
    Remove Duplicates from Sorted Array
    Populating Next Right Pointers in Each Node
    Minimum Depth of Binary Tree
    Unique Paths
    Sort Colors
    Swap Nodes in Pairs
    Merge Two Sorted Lists
    Climbing Stairs
  • 原文地址:https://www.cnblogs.com/sxy-798013203/p/7635397.html
Copyright © 2011-2022 走看看