zoukankan      html  css  js  c++  java
  • 118. 119. Pascal's Triangle -- 杨辉三角形

    118.

    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]
    ]
    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> ans;
            if(numRows < 1)
                return ans;
            vector<int> pre, cur;
            pre.push_back(1);
            ans.push_back(pre);
            for(int i = 1; i < numRows; i++)
            {
                cur.push_back(1);
                for(int j = 0; j < pre.size()-1; j++)
                {
                    cur.push_back(pre[j]+pre[j+1]);
                }
                cur.push_back(1);
                ans.push_back(cur);
                pre = cur;
                cur.clear();
            }
            return ans;
        }
    };

    119.

    Given an index k, return the kth row of the Pascal's triangle.

    For example, given k = 3,
    Return [1,3,3,1].

    class Solution {
    public:
        vector<int> getRow(int rowIndex) {
            vector<int> ans(rowIndex+1, 0);
            ans[0] = 1;
            for(int i = 1; i <= rowIndex; i++)
            {
                ans[i] = 1;
                for(int j = i-1; j > 0; j--)
                {
                    ans[j] += ans[j-1];
                }
            }
            return ans;
        }
    };

    只开一个数组,从后向前计算。

  • 相关阅读:
    HDU 1017—A Mathematical Curiosity
    N !
    L
    J
    Danganronpa
    A water problem
    hdu 5461 Largest Point
    India and China Origins hdu 5652 (BFS+二分)
    D (多校训练三) poj1919 (二分)
    Discovering Gold lightoj 1030 (dp+期望)
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5450160.html
Copyright © 2011-2022 走看看