Leetcode算法学习日志-62 Unique Paths

来源:互联网 发布:小猪o2o源码下载 编辑:程序博客网 时间:2024/06/01 14:54

Leetcode 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.

题意分析

要从start处到Finish处,每次只能向右一步或向下一步,求总共有多少种不同的走法。

解法分析

本题采用两种方法:

  • 动态规划
  • 数学方法

动态规划

本题是一个典型的动态规划题目,令P(i,j)为到坐标为i,j的点需要的步数,则P(i,j)=P(i-1,j)+P(i,j-1),这就是递归式,给定初始条件P(0,j)=1,P(i,0)=1.利用这个递归式就能求得P(m-1,n-1)。C++代码如下:

class Solution {public:    int uniquePaths(int m, int n) {        int i,j;        vector<int> pre(n,1);        vector<int> cur(n,1);        for(i=1;i<m;i++){            for(j=1;j<n;j++){                //P[i][j]=P[i-1][j]+P[i][j-1];                   cur[j]=cur[j-1]+pre[j];            }            swap(pre,cur);        }        return pre[n-1];       }};
注意到递归式P(i,j)=P(i-1,j)+P(i,j-1)并不需要用到整个P矩阵,而是其中的两行,所以只需要用cur和pre两行来当做中间量。再仔细观察
cur[j]=cur[j-1]+pre[j]
pre其实是cur之前的值,因此不必用两个vector,只用一个cur即可,代码如下:

class Solution {    int uniquePaths(int m, int n) {        if (m > n) return uniquePaths(n, m);        vector<int> cur(m, 1);        for (int j = 1; j < n; j++)            for (int i = 1; i < m; i++)                cur[i] += cur[i - 1];         return cur[m - 1];    }}; 
这样空间复杂度就变为O(min(m,n)).

数学方法

本题总的需要走的步数为m+n-2,其中向下n-1步,向右m-1步,先找出m和n中较小的数,减一后再利用公式C(m,n)=(m+n)!/m!*n!。注意由于m,n可能较大,直接计算阶乘很快超出int的范围,所以应该变乘边除,并将中间结果存储在long int中。C++代码如下:

class Solution {    public:        int uniquePaths(int m, int n) {            int N = n + m - 2;// how much steps we need to do            int k = m - 1; // number of steps that need to go down            long res = 1;            // here we calculate the total possible path number             // Combination(N, k) = n! / (k!(n - k)!)            // reduce the numerator and denominator and get            // C = ( (n - k + 1) * (n - k + 2) * ... * n ) / k!            for (int i = 1; i <= k; i++)                res = res * (N - k + i) / i;            return (int)res;        }    };
要充分利用
 res = res * (N - k + i) / i;
乘除次数相同的特点。





原创粉丝点击