2차원 DP 문제이다. 로봇은 좌상단에서 시작해 우측, 또는 아래로만 이동할 수 있으므로 첫 행, 첫 열은 가는 방법이 한 가지로 고정이다. 해당 조건에서 안쪽 좌표들의 경우 좌측에서 오는 경우와 위에서 오는 경우 두 가지 경우의 합이 해당 좌표로 가는 방법이기에 해당 조건으로 점화식을 세워 문제를 해결할 수 있었다.

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

 

https://leetcode.com/problems/climbing-stairs/description/

 

Climbing Stairs - LeetCode

Can you solve this real interview question? Climbing Stairs - You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?   Example 1: Input: n = 2 Outpu

leetcode.com

 

계단을 1, 2 단씩 오를수 있을때 n계의 계단을 오르는 방법의 개수를 묻는 DP 문제이다.
n번재 계단을 오르기 위해선 n-1 번째에서 한 걸음, n-2 에서 두 걸음 오르는 방법이 있으므로

해당 방식으로 dp 점화식을 만들어 문제를 해결하였다.

public class Solution {  
    public int climbStairs(int n) {  
        int[] dp = new int[46];  
        dp[0] = 0;  
        dp[1] = 1;  
        dp[2] = 2;  
  
        for(int i = 3; i <= n; i++){  
            dp[i] = dp[i - 2] + dp[i - 1];  
        }  
  
        return dp[n];  
    }  
}

+ Recent posts