코딩 테스트/LeetCode(swift)

[LeetCode] 62. Unique Paths

Skillist 2022. 2. 19. 21:14
반응형

문제

https://leetcode.com/problems/unique-paths/

 

Unique Paths - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

———————————————————————————

 

코드

class Solution {
    func uniquePaths(_ m: Int, _ n: Int) -> Int {
        var map: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: m)
    
        for x in 0..<n {
            map[0][x] = 1
        }
    
        for y in 1..<m {
            for x in 0..<n {
                var count = 0
                let up = y - 1 
                count += map[up][x]
            
                let left = x - 1
                if left >= 0 {
                    count += map[y][left]
                }
                map[y][x] = count
            }
        }
        return map[m-1][n-1]
    }
}

———————————————————————————

 

설명

경로는 down과 right만 가능하니,

윗칸의 경로수와 오른쪽 칸의 경로수를 더하여 쭉쭉 나가면 됩니다.

———————————————————————————

 

회고

너무 쉬운거 같은데 제가 잘못 접근한건가요?;;;;;

반응형