LeetCode OJ 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?

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

Note: m and n will be at most 100.


【题目分析】

给定一个m*n的grid,机器人从左上角出发到达右下角,每次只能向右或者向下移动一步,则到达右下角的不同的路线有多少条?


【思路】

1. 组合数学的思想

在组合数学中关于这个问题有一个专门的讨论,作为组合数入门的一个引入题目。原题目是从坐标点(0, 0)出发,到达另外一个点(m, n)的不同路径有多少条,其中m >= 0, n>=0。

组合数学的思想是这样的,从(0, 0)到达(m, n),无论无论怎么走,总的步数是确定的:m + n,而且肯定是向右移动了m步,向上移动了n步。那么我们先选定向右移动的m步,则剩下的n步就是确定的。所以这是一个组合数C(m+n, m) 或者 C(m+n, n)。

2. 动态规划的思想

动态规划的思想就是在移动过程中计算出到达的每一个小格子的方法数。

(1)到达最上边和最右边方格的方法数是1;

(2)以后到达每一个方格的方法数由它左边和上边的方法数确定,因为我们只能向右和向下移动;结果如下:


【java代码】组合法——由于计算过程中可能会遇到很大的数,要注意溢出的问题。

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3         m--; n--;
 4         int mn = m + n;
 5         int num = Math.min(m ,n);
 6         double ans = 1;
 7         for(int i=0;i<num;i++)
 8             ans = ans * ((double)(mn - i) / (num-i));
 9         return (int)Math.round(ans);
10     }
11 }

【java代码】动态规划

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3         int[] dp = new int[m];
 4         dp[0] = 1;
 5         for (int i = 0; i < n; i++)
 6             for (int j = 1; j < m; j++)
 7                 dp[j] = dp[j - 1] + dp[j];
 8         return dp[m - 1];
 9     }
10 }

 

posted @ 2016-05-27 10:42  Black_Knight  阅读(201)  评论(0编辑  收藏  举报