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

来源:互联网 发布:java 线程优先级 编辑:程序博客网 时间:2024/06/03 17:42

题目描述

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;i<m;i++){            F[i][0]=1;        }        for(int j=0;j<n;j++)            F[0][j]=1;        for(int i=1;i<m;i++){            for(int j=1;j<n;j++)            {                //F[i][j]为到这个点的路径有几条                F[i][j]=F[i-1][j]+F[i][j-1];            }        }        return F[m-1][n-1];    }}