[LeetCode 119] Pascal's Triangle II
LeetCode 119 (Java)
[Pascal's Triangle II] 문제 풀이
[LeetCode 119] Pascal's Triangle II
Description
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 1
- Input: rowIndex = 3
- Output: [1,3,3,1]
Example 2
- Input: rowIndex = 0
- Output: [1]
Example 3
- Input: rowIndex = 1
- Output: [1,1]
Constraints
0 <= rowIndex <= 33
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public List<Integer> getRow(int rowIndex) {
int[][] triangle = new int[100][100]; // 실제 연산용 변수
List<Integer> result = new ArrayList<>(); // 리턴용 변수
for (int i = 0; i < (rowIndex + 1); i++) {
triangle[i][0] = 1; // 초기값 지정
triangle[i][i] = 1; // ,,
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
for (int i = 0; i < triangle.length; i++) { // rowIndex의 값 저장
if (i == rowIndex) {
for (int j = 0; j < (i + 1); j++) {
result.add(triangle[i][j]);
}
}
}
return result;
}
}
| Runtime | Memory |
|---|---|
| 1 ms | 42.5 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public long findNcR(int n , int r){
long res = 1;
for(int i = 0; i < r; i++){
res = res*(n-i);
res = res/(i+1);
}
return res;
}
public List<Integer> getRow(int rowIndex) {
List<Integer> ans = new ArrayList<>();
for(int i = 0; i <= rowIndex ; i++){
ans.add((int)findNcR(rowIndex , i));
}
return ans;
}
}
Reference
This post is licensed under CC BY 4.0 by the author.

