zoukankan      html  css  js  c++  java
  • (leetcode题解)Pascal's Triangle

    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]
    ]

    题意实现一个杨辉三角。

    这道题只要注意了边界条件应该很好实现出来,C++实现如下

        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> res;
            res.resize(numRows);
            for(int i=0;i<numRows;i++)
            {
                res[i].push_back(1);
                for(int j=1;j<i;j++)
                {
                    res[i].push_back(res[i-1][j-1]+res[i-1][j]);
                }
                if(i!=0)
                    res[i].push_back(1);
            }
            return res;
        }

    Pascal's Triangle II

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

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

    Note:
    Could you optimize your algorithm to use only O(k) extra space?

    题意是给一个k值,返回杨辉三角的第k+1行,要求空间复杂度是O(k)。

    这道题的其实本质与上一道一样求杨辉三角,申请一个空间保存上一行的值即可,C++实现如下:

    vector<int> getRow(int rowIndex) {
            vector<int> res,temp;
            res.resize(rowIndex+1);
            for(int i=0;i<rowIndex+1;i++)
            {
                res[0]=1;
                for(int j=1;j<i;j++)
                {
                    res[j]=temp[j-1]+temp[j];
                }
                if(i!=0)
                    res[i]=1;
                temp=res;
            }
            return res;
        }
  • 相关阅读:
    Add two numbers
    House Robber && House Robber II
    Clone Graph
    224. Basic Calculator
    29. Divide Two Integers
    365. Water and Jug Problem
    435. Non-overlapping Intervals
    452. Minimum Number of Arrows to Burst Balloons
    138. Copy List with Random Pointer
    43. Multiply Strings
  • 原文地址:https://www.cnblogs.com/kiplove/p/6986598.html
Copyright © 2011-2022 走看看