Home LeetCode - 119. Pascal's Triangle II
Post
Cancel

LeetCode - 119. Pascal's Triangle II

119. Pascal’s Triangle II - Easy

문제

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

example

제한사항

  • 0 <= rowIndex <= 33

입출력 예

1
2
3
4
Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]
1
2
3
4
Example 2:

Input: rowIndex = 0
Output: [1]
1
2
3
4
Example 3:

Input: rowIndex = 1
Output: [1,1]

풀이

  • Dynamic Programming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if (rowIndex == 0) {
            return {1};
        } else if (rowIndex == 1) {
            return {1, 1};
        }

        vector<vector<int>> item(rowIndex + 1, vector<int>(rowIndex + 1, 1));
        for (auto i = 2 ; i <= rowIndex ; ++i) {
            for (auto j = 1 ; j < i ; ++j) {
                item[i][j] = item[i - 1][j - 1] + item[i - 1][j];
            }
        }
        
        return item.back();
    }
};
This post is licensed under CC BY 4.0 by the author.