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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

 

大脑空白下给的答案,二话不说TLE

public class Solution {
    public int uniquePaths(int m, int n) {
        if(m==0 || n==0) return 0;
        if(m==1 || n==1) return 1;
        return uniquePaths(m-1,n) + uniquePaths(m, n-1);
    }
}

清晰的解法和思路参考

http://codeganker.blogspot.com/2014/03/unique-paths-leetcode.html

 soln 1 O(min(m,n)) space, time O(m*n)

public class Solution {
    public int uniquePaths(int m, int n) {
    int x = Math.min(m,n);
    int y = Math.max(m,n);
    int[] res= new int[x];
    res[0]=1;
    for(int i=0; i<y; i++){
        for(int j=1; j<x;j++){
            res[j] += res[j-1];
        }
    }
    return res[x-1];
    }
}

soln 2 引用code ganker"其实就是机器人总共走m+n-2步,其中m-1步往下走,n-1步往右走,本质上就是一个组合问题,也就是从m+n-2个不同元素中每次取出m-1个元素的组合数。根据组合的计算公式,我们可以写代码来求解即可。"

public class Solution {
    public int uniquePaths(int m, int n) {
    int x = Math.min(m,n);
    int y = Math.max(m,n);
    double res=1;
    double d=1;
    for(int i=x+y-2; i>y-1; i--){ 
        res *= i;
        d  *= (i-y+1); // X!/(Y!*(X-Y)!)       
    }     
    return (int) (res/d);
    }
}

 

posted @ 2015-04-15 03:31  世界到处都是小星星  阅读(130)  评论(0编辑  收藏  举报