LeetCode 62. Unique Paths(java)

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?
LeetCode 62. Unique Paths(java)_第1张图片
Above is a 3 x 7 grid. How many possible unique paths are there?

解法:动态规划,用一个数组来存储每个格子上的路径数量,规则是:每个格子上的数量为上面格子的数量加上左边格子的数量(因为机器人只能往又走和往下走),所以一定是通过上面一个格子或者左边一个格子走到当前格子的,因此当前格子的数量为从左边走过来的路径数+从上面走过来的路径数。
代码:
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++) {
            dp[0] = 1;
            for (int j = 1; j < n; j++) {
                dp[j] = dp[j] + dp[j-1];
            }
        }
        return dp[n-1];
    }

你可能感兴趣的:(dp)