728x90
문제
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
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 <= 40
필요한 크기의 arr 2차원 베열을 만들어서 전부 iteration 하며
f(i,j) = f(i-1, j-1) + f(i-1, j) 식을 적용했다.
class Solution {
func getRow(_ rowIndex: Int) -> [Int] {
// 1
// 1 1
// 1 2 1
// 1 X 3 1
// 1 4 4 4 1
// if i is 0 or end == 1
// else
// f(i,j) = f(i-1, j-1) + f(i-1,j)
// [1]
// [1, 1]
// [1, 2, 1]
// [1. 3. 3. 1]
var arr : [[Int]] = []
for i in 1...rowIndex+1 {
arr.append(Array(repeating: 1, count: i))
}
for i in 0..<arr.count {
for j in 0..<arr[i].count {
if j != 0 && j != arr[i].count-1 {
arr[i][j] = arr[i-1][j-1] + arr[i-1][j]
}
}
}
return arr[rowIndex]
}
}
728x90
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode - Remove Duplicates from Sorted Array (0) | 2020.09.11 |
---|---|
LeetCode - Fibonacci Number, Climbing Stairs (0) | 2020.09.10 |
LeetCode - Search in Binary Search Tree (0) | 2020.09.10 |
LeetCode - Reverse Linked List 🤦🏻 (0) | 2020.09.09 |
LeetCode - Swap Nodes in Pairs (0) | 2020.09.03 |
댓글