欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LeetCode]118. Pascal's Triangle

程序员文章站 2024-02-20 23:25:46
...

[LeetCode]118. Pascal’s Triangle

题目描述

[LeetCode]118. Pascal's Triangle

思路

水题,根据前数组计算当前数组

代码

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        /*
        vector<vector<int>> res;
        for (int i = 0; i < numRows; ++i) {
            vector<int> temp;
            if (i < 2)
                for (int j = 0; j <= i; ++j) 
                    temp.push_back(1);
            else {
                int left = 0, right = 1;
                for (int j = 0; j <= i; ++j) {
                    if (j == 0 || j == i)
                        temp.push_back(1);
                    else
                        temp.push_back(res[i - 1][left++] + res[i - 1][right++]);
                }
            }
            res.push_back(temp);
        }
        return res;
        */
        vector<vector<int>> res(numRows);
        for (int i = 0; i < numRows; ++i) {
            res[i].resize(i + 1);
            res[i][0] = 1;
            res[i][i] = 1;

            for (int j = 1; j < i; ++j) {
                res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
            }
        }
        return res;
    }
};

int main() {
    vector<vector<int>> res;
    Solution s;
    res = s.generate(5);

    for (auto vec : res) {
        for (int num : vec)
            cout << num << " ";
        cout << endl;
    }

    system("pause");
    return 0;
}
相关标签: leetcode