EP43-Dynamic Programming-Unique Paths

Here is another problem that can be solved by using Dynamic Programming.

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?
Note: m and n will be at most 100.

EP43-Dynamic Programming-Unique Paths_第1张图片
robot_maze.png

As I told you just just now, this is also a dp issue. Think about it:
From the first row(a[0,0~m]) and first column(a[0~n,0]) we can go to every grid. And if you wanna get to the grids of the first row/cow there is always just only one path because we said that you can only go from your left or top grid.
We can imitate the LIS's state transfer equation:
LIS(i)=max{LIS(j)+1} ,j
But we got two variants here called m & n, how to deal with it? Actually its totally different..
If you want to go to (m,n), you can only go there from (m-1,n) or (m , n-1).So, there's :
Paths(m,n) = Paths(m-1, n) + Paths(m ,n -1)

So, there is:

    public int uniquePaths(int m, int n) {
        // DP with 2 dimensions array
        int[][] a = new int[m][n];
        for (int i = 0; i < m; i++) {
            a[i][0] = 1;
        }
        for (int i = 0; i < n; i++) {
            a[0][i] = 1;
        }
        //start computing from the second row/column
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                a[i][j] = a[i - 1][j] + a[i][j - 1];
            }
        }
        return a[m - 1][n - 1];
    }

Two numbers are saved: a[i - 1][j] and a[i][j - 1].
We can optimize this method. It's a little bit hard to understand.
You may noticed that the first row/col are both 1,1,1,... So we can make reuse the first row as the first col.

public class Solution {
    public int uniquePaths(int m, int n) {
        // DP with 1 dimension array
        int[] a = new int[n];
        for (int j = 0; j < n; j++) {
            a[j] = 1;
        }
      //start from the 2nd row
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                a[j] += a[j-1];
            }
        }
        return a[n-1];
    }
}

你可能感兴趣的:(EP43-Dynamic Programming-Unique Paths)