[Leetcode学习-java]Unique Paths(唯一路径)

问题:

难度:easy

说明:

机器人只能在给出的二维数组地图,向左向下移动,统计所有可能的运动路径数量,水题。

问题链接:https://leetcode.com/problems/unique-paths/

相关算法:

P1002-过河卒:https://blog.csdn.net/qq_28033719/article/details/106261183

输入案例:

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 -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

我的代码:

现在学习了dp,这个就是经典的dp题目(你也可以叫记忆化搜索),所以做过之后就是简单题了。

不过dp状态转移还是难点:DP[ i ][ j ] = DP[ i - 1 ][ j ] + DP[ i ][ j - 1 ]

当前通过数 = 上面的可能通过数 + 左边面可能通过数

可以查看背包问题,了解一维二维数组处理

背包问题&一百块最少硬币数:https://blog.csdn.net/qq_28033719/article/details/106501253

1、用二维数组做

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];
    }
}

2、节省空间用一维数组做(通常一维能做,滚动数组也能做)

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

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

        return dp[n - 1];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107033638