[leetcode #62] Unique Paths

Seongyeol Shin·2021년 11월 22일
0

leetcode

목록 보기
84/196
post-thumbnail

Problem

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Example 1:

Input: m = 3, n = 7
Output: 28

Example 2:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

Example 3:

Input: m = 7, n = 3
Output: 28

Example 4:

Input: m = 3, n = 3
Output: 6

Constraints:

・ 1 <= m, n <= 100
・ It's guaranteed that the answer will be less than or equal to 2 * 10⁹.

Idea

backtracking과 dp를 이용해서 풀 수 있는 문제다.

도착점까지 도착할 때까지 로봇은 오른쪽으로 아래쪽으로만 이동할 수 있다. backtracking을 생각해보면 도착점에서 왼쪽과 위쪽으로는 도착할 수 있는 방법이 오직 한 가지밖에 없다는 것을 알 수 있다.

dp를 m x n까지 만든 다음, 위 원리에 따라 가장 아래쪽 row와 가장 오른쪽 column의 값을 전부 1로 설정한다.

dp의 다른 원소값은 오른쪽과 아래쪽을 더한 값이 된다. 그 이유는 로봇이 오른쪽과 아래쪽 두 방향 모두 이동이 가능하기 때문이다.

먼저 설정한 값을 제외하고 아래쪽 row와 오른쪽 column을 가진 원소에서 시작해 column을 왼쪽으로 이동하여 값을 설정하고 위쪽 row로 이동한다.

위 과정을 반복하면 모든 dp 값이 채워지며, dp[0][0]을 리턴하면 된다.

Solution

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        for (int i=0; i < n; i++) {
            dp[m-1][i] = 1;
        }

        for (int i=0; i < m; i++) {
            dp[i][n-1] = 1;
        }

        for (int i=m-2; i >= 0; i--) {
            for (int j=n-2; j >= 0; j--) {
                dp[i][j] = dp[i+1][j] + dp[i][j+1];
            }
        }

        return dp[0][0];
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글