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?

 

方法1 DP(动态规划)

因为只有两个方向,所以每个点其实只是上面点路径数和左边点路径数的和,当然要判断下数组越界。

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3          int[][] path=new int[m][n];
 4         path[0][0]=1;
 5         for(int i=0;i<m;i++){
 6             for(int j=0; j<n;j++){
 7                 if(i-1>=0){
 8                     path[i][j] += path[i-1][j];
 9                 }
10                 if(j-1>=0){
11                     path[i][j] += path[i][j-1];
12                 }
13             }
14         }
15         return path[m-1][n-1];
16     }
17 }

方法2 DFS(深度优先遍历)

一看地图问题,想到用深度优先,遍历每一个位置都只有两个选择,向下和向右,发现走到头返回。

 

public class Solution {
   public static int uniquePaths_helper(int mm, int nn,int m,int n,int sum) {
        if (mm==m-1&&nn==n-1){
            sum++;
            return sum;
        }
        if (mm<0||mm>=m){
            return sum;
        }
        if (nn<0||nn>=n){
            return sum;
        }
        int sum1=uniquePaths_helper(mm+1,nn,m,n,sum);
        return uniquePaths_helper(mm,nn+1,m,n,sum1);
    }
    public static int uniquePaths(int m, int n) {
        return uniquePaths_helper(0,0,m,n,0);
    }
   
}

 

posted on 2017-07-03 13:52  sure0328  阅读(82)  评论(0)    收藏  举报

导航