Leetcode_62_uniquePaths_행렬의 총 경로

package DP;

public class _62_uniquePaths {
    //1.  dp
    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 j = 0; j < n; j++){
            dp[0][j] = 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];
    }

    //2.    
    public int uniquePaths2(int m, int n){
        return helper(0, 0, m, n, new int[m][n]);
    }
    private int helper1(int i, int j, int m, int n){
        if (i == m-1 && j == n-1){
            return 1;
        }
        return helper1(i+1, j, m, n) + helper1(i, j+1, m, n);
    }
    private int helper(int i, int j, int m, int n, int[][] mem){
        if (i == m-1 && j == n-1){
            return 1;
        }else if (mem[i][j] > 0){
            return mem[i][j];
        }else{
            mem[i][j] = helper(i+1, j, m, n, mem) + helper(i, j+1, m, n, mem);
        }
        return mem[0][0];
    }
}

좋은 웹페이지 즐겨찾기