LeetCode之机器人移动(动态规划)

题目描述

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?

Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.

本题是求解机器人按指定可移动路径所有可以走的总路径数,每一步只能向右或者向下,相当于从每一点移动有两条路径可走,
不妨逆向思考下,走到当前点的路径数是到达其左边和上边路径数之和。那么状态转移方程就确定了,设到达每一点的路径数为F[i][j] (i,j分别为行数和列数), 则F[i][j]=F[i-1][j]+F[i][j-1]。
所以到达最右端底部的路径数即为F[m-1][n-1](建立一个二维数组[m][n]),代码如下。

public class Solution {
    public int uniquePaths(int m, int n) {
        if(m==0||n==0)
            return 1;
        int[][] F=new int[m][n];
        for(int i=0;i0]=1;
        }
        for(int j=0;j0][j]=1;
        for(int i=1;ifor(int j=1;j//F[i][j]为到这个点的路径有几条
                F[i][j]=F[i-1][j]+F[i][j-1];
            }
        }
        return F[m-1][n-1];
    }
}

你可能感兴趣的:(Java,leetcode,动态规划)