LeetCode ---- 62、不同路径

题目链接

思路:

动态规划思路。

由于每一步都只能向右或者向下走,所以每一步都依赖于左边和上边,

走到当前的位置,可以走的路径总数    等于     走到当前位置左边格子的路径总数   +     走到当前位置上边格子的路径总数。

推出动态方程:dp[ i ][ j ] = dp[ i - 1 ][ j ] + dp[ i ][ j - 1 ];

初始时,dp[0][0] = 1, dp[ i ][ 0 ] = 1, dp[ j ][ 0 ] = 1

    public int uniquePaths(int m, int n) {
        if (m == 1 || n == 1) {
            return 1;
        }
        int[][] path = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    path[i][j] = 1;
                } else {
                    path[i][j] = path[i - 1][j] + path[i][j - 1];
                }
            }
        }
        return path[m - 1][n - 1];
    }

代码参考自:https://leetcode-cn.com/problems/unique-paths/comments/1993

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/106796731