1 minute read

ProblemPermalink

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 10^9.

Example 1:

image

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

Constraints:

  • 1 <= m, n <= 100

SolutionPermalink

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] grid = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                if (i == 0)
                    grid[i][j] = 1;
                else if (j == 0)
                    grid[i][j] = 1;
                else if (i != 0 && j != 0)
                    grid[i][j] = grid[i][j - 1] + grid[i - 1][j];
            } return grid[n - 1][m - 1];
    }
}

ExplanationPermalink

  • m x n 그리드를 나타내기 위해 2차원 배열 grid를 선언한다.
    int[][] grid = new int[n][m];
    
  • grid[n][m]요소로 가기위한 경우의 수는 grid[n][m] 위에 위치한 요소로 가는 경우의 수와 grid[n][m] 왼쪽에 위치한 요소로 가는 경우의 수를 더한 것과 같다.
  • 다음은 예시를 나타낸 것이다.
    grid    
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
  • 위의 예시처럼 2차원 배열 grid를 채우기 위해 for 반복문 2개를 중첩한다.
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) {
          if (i == 0)
              grid[i][j] = 1;
          else if (j == 0)
              grid[i][j] = 1;
          else if (i != 0 && j != 0)
              grid[i][j] = grid[i][j - 1] + grid[i - 1][j];
      }
    
  • 그리드의 가장 우측 하단의 값을 반환한다.
    return grid[n - 1][m - 1];
    

Categories:

Updated:

Leave a comment