leetCode-Unique Paths

来源:互联网 发布:网络追逃人员查询系统 编辑:程序博客网 时间:2024/06/11 00:23

Description:
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.

Solution:

#设c[x][y]为从00到(x,y)可能的路径,c[x][y] = c[x][y - 1] +c[x - 1][y],而第0行和第0列由于只能往右或者往下,所以都设置为1 public class Solution {    public int uniquePaths(int m, int n) {        int[][] map = new int[m][n];        for(int i = 0; i<m;i++){            map[i][0] = 1;        }        for(int j= 0;j<n;j++){            map[0][j]=1;        }        for(int i = 1;i<m;i++){            for(int j = 1;j<n;j++){                map[i][j] = map[i-1][j]+map[i][j-1];            }        }        return map[m-1][n-1];    }}

Best Solution:

//相当于把上面例子的二维数组缩短成一维数组了class Solution {    public int uniquePaths(int m, int n) {        int[] row = new int[n];        Arrays.fill(row,1);        for ( int i = 1; i < m; i++){            for ( int j = 1; j < n; j++){                row[j]+=row[j-1];            }        }        return row[n-1];    }}

总结:
这一题是典型的动态规划。我们首先可以想到递归,而递归一个问题就是有重复计算,我们可以想到用一个数组保存计算过的c[x][y],等到下次遇上的时候直接取值即可,效率会大大提高,但是还是不够好,因为递归有栈帧的问题,于是我们想到将递归转化为递推,既然每个c[x][y]=c[x - 1][y] + c[x][y - 1],那么我们可以把第一行,第一列的c[x][y]先求出来,然后遍历接下来的矩阵,用这个转化公式求值即可。
可以看一下这篇文章,动态规划讲的比较详细:
http://blog.csdn.net/baidu_28312631/article/details/47418773

原创粉丝点击