LeetCode 118. Pascal's Triangle

题目描述

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:
Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

题目思路

代码 C++

  • 思路一、
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        vector<int> a;
        vector<int> b;
        
        for(int i=1; i <= numRows; i++){
            if(i == 1){
                a.push_back(1);
                result.push_back(a);
            }
            else if(i == 2){
                b.push_back(1);
                b.push_back(1);
                result.push_back(b);
            }
            else{
                a.clear();
                a.push_back(1);
                for(int i=0; i < b.size()-1; i++){
                    a.push_back(b[i]+b[i+1]);
                }
                a.push_back(1);
                result.push_back(a);
                b = a;
            }
        }
        
        return result;
    }
};
  • 思路二、
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result(numRows);
        
        for(int i=0; i < numRows; i++){
            result[i].resize(i+1);
            result[i][0] = result[i][i] = 1;
            
            for(int j=1; j < i; j++){
                result[i][j] = result[i-1][j-1] + result[i-1][j];
            }
        }
        
        return result;
    }
};

总结展望

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 Given a non-negative integer numRows, generate the fir...
    njim3阅读 1,306评论 0 0
  • android中有很多需要数据交互的部分,交互的方式也有很多种不同,四大组件各有各的方法, 今天主要是谈谈关于回调...
    sososun阅读 11,578评论 0 8
  • 在年少的岁月里,我们曾无限的幻想;自己有一天会不会像小鸟一样,在空中划过一道弧线。会不会像风一样,四处飘散,没有方...
    巷北狸猫O阅读 3,177评论 5 11
  • 爱情是什么? 是心动?激情?缠绵? 抑或是心碎?凄美?别离? 还是欢乐?眼泪?感动? 也许,都是 也许,都不是 爱...
    夏沨阅读 1,328评论 0 2

友情链接更多精彩内容