본문 바로가기
Algorithm/LeetCode

LeetCode - Pascal's Triangle II

by HaningYa 2020. 9. 10.
728x90

 


문제

Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.

Notice that the row index starts from 0.

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

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

댓글