UniquePath

  • 2022-12-14
  • 浏览 (556)

UniquePath.java 源码

package algorithm.dp;

import java.util.Arrays;

/**
 * 不同路径
 */
public class UniquePath {
    
    public int uniquePaths1(int m, int n) {
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dp[i][j] = i == 0 || j == 0 ? 1 : dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m - 1][n - 1];
    }

    /**
     * 简化一维的写法
     */
    public int uniquePaths2(int m, int n) {
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] += dp[j - 1];
            }
        }
        return dp[n - 1];
    }
}

你可能感兴趣的文章

CoinChange

EditDistance

HouseRobber

0  赞