【LeetCode】(63)Unique Paths (Medium)

题目

Unique Paths

  Total Accepted: 55087  Total Submissions: 166926 My Submissions

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.














解析

我一看到这个题目,脑海里冒出来的就是数学思维。例如7x3的格子,你需要走的步数一共是(7-1)+(3-1) = 8,理由是因为走的时候是从一个格子走到另一个格子算作一步。

一共走这么多步,但是有(7-1)步是横着走的。其实我们只需要从这8步中选出哪6步是横着走的就可以了,也就是数学公式排列组合的C{6,8}

总结一下

假设是m x n的矩形,我们不妨默认m<=n

则步数一共是


因此只要实现阶乘的运算就可以了,不过麻烦的是阶乘的运算会溢出,我的办法是用double型来计算,最后accept了。

class Solution {
public:

	 double CountPai(double a,double b)
	 {
		 double sum = 1;
		 while (a != b)
		 {
			 sum = a * sum;
			 a ++;
		 }
		 return sum*a;
	 }
    int uniquePaths(int m, int n) {
         m--;n--;
		 if(m*n==0) 
		   return 1;
		 if (m>=n)
		 {
			 double a = CountPai(m+1,m+n);
			 double b = CountPai(1,n);
			 return (int)(a/b);
		 }
		 else
		 {
			 double a = CountPai(n+1,m+n);
			 double b = CountPai(1,m);
			 return (int)(a/b);
		 }
    }
};

这是一种纯数学的方法。

其实用动态规划的思路就很简单了,理论上建立一个二维数组path[i][j],表示到i,j位置的元素的路径有多少个。

则显然path[0][j]都是1,path[i][0]也都是1,

path[i][j] = path[i-1][j] + path[i][j-1]

再节省空间一下,其实一维数组就足够了,从第一行开始扫描,后面的去累加就行

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> path(n,1);

		for (int i = 1;i<m;i++)
		{
			for (int j = 1;j<n ;j++)
			{
				path[j] +=  path[j-1];
			}
		}
		return path[n-1];
    }
};









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值