动态规划从入门到精通(二)-棋盘类题目

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38278878/article/details/81129034

题目:Leetcode 62. Unique Paths

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?
这里写图片描述

题目的意思: 有个棋盘如上图,机器人每次能向下走一格或者向右走一格,从左上角走到右下角有多少走法

例如:输入: m = 3, n = 2 ,即一个3*2的棋盘
1. 右 -> 右 -> 下
2. 右 -> 下 -> 右
3. 下-> 右-> 右
一共三种走法,所以输出 3

分析:从题意可以得知这是最优解的题目,由于题目涉及棋盘,所以我们画3*2的图进行分析:
这里写图片描述
由图可知,左上角为起点,右下角为终点。然后参考动态规划从入门到精通(一)-入门篇的步骤,将这个大问题拆解为小问题。
仔细观察棋盘,可以得出一个结论,走到终点所需的最小步数等于“走到终点左方位置所需的最小步数”与“走到终点上方位置所需的最小步数”的和,即上图中两个菱形的位置。
以此类推,不断拆分,可以得出递推式,也就是状态转移方程,f(m,n) = f(m-1,n) + f(m,n-1)

之后就是讨论底层的边界问题f(0,0),f(0, y),f(x, 0),f(0,0)为起点,所以f(0,0)=0;f(0, y)代表棋盘第一行,以这一行为棋盘,只能往右走,只有一种走法,所以有f(0,y) = 1;同理有f(x,0) = 1;

代码如下:

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] tab = new int[m][n];
        //f(0,0)为起点,所以f(0,0)=0
        tab[0][0] = 0;
        //f(0, y)代表棋盘第一行,若以这一行为棋盘,只能往右走,只有一种走法,所以有f(0,y) = 1;
        for(int i = 0; i < n; i++)
            tab[0][i] = 1;
        //f(x, 0)代表棋盘第一列,若以这一列为棋盘,只能往下走,所以有f(x,0) = 1;
        for(int i = 0; i < m; i++)
            tab[i][0] = 1;

        //用状态转移方程迭代
        for(int i = 1; i < m; i++) {
            for(int j = 1; j < n; j++) {
                tab[i][j] = tab[i - 1][j] + tab[i][j - 1];
            }
        }
        return tab[m-1][n-1];
    }
}

总结:棋盘类的题目都可以用这种拆解棋盘的方法,如Leecode 64. Minimum Path Sum,区别只是在于状态转移方程比f(m,n) = f(m-1,n) + f(m,n-1)多出一些条件。

猜你喜欢

转载自blog.csdn.net/weixin_38278878/article/details/81129034