LeetCode - Unique Paths

Unique Paths

2013.12.21 02:43

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.

Solution:

  It's obviously a dynamic programming problem, with the recurrence relations expressed as: a[x][y] = a[x - 1][y] + a[x][y - 1], a[0][0] = 1;

  Using this formula will give you a solution in O(m * n) time. If you think one step further, you'll see this is the Pascal Triangle, thus each term in the triangle can be calculated with combinatorials, namely C(m + n - 2, m - 1).

  To travel from (0, 0) to (m - 1, n - 1), you'll have to move (m - 1) steps down and (n - 1) steps right. Then comes the question: in the (m + n - 2) moves you make, which of them are down and which of them are right. The number of ways to choose is the answer we're looking for.

  Time complexity is O(m) or O(n) or O(min(m, n)), depending on how you write the code to calculate the combinatorial. Space compelxity is O(1).

Accepted code:

 1 class Solution {

 2 public:

 3     int uniquePaths(int m, int n) {

 4         // IMPORTANT: Please reset any member data you declared, as

 5         // the same Solution instance will be reused for each test case.

 6         if(m > n){

 7             return uniquePaths(n, m);

 8         }

 9         

10         // 1WA here, integer overflow

11         long long int sum, res;

12         

13         // 1WA here, m and n start from 0, not 1

14         --m;

15         --n;

16         sum = res = 1;

17         // 1CE here, int i is not declared

18         for(int i = 1; i <= m; ++i){

19             sum *= i;

20             res *= (m + n + 1 - i);

21             if(res % sum == 0){

22                 res /= sum;

23                 sum = 1;

24             }

25         }

26         

27         return res;

28     }

29 };

 

 

你可能感兴趣的:(LeetCode)