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.

此题思路有3种!

1、直接数学公式,用组合的方法,直接用(M+N-2)!/(M-1)!*(N-1)!  意思是 水平方向有 n-1 中选择,垂直方向 m-1中选择。所以总体有 m+n-2,只需在这m+n-2种方式选择向右走 n-1 步或者 向下的m-1  步即可。注意实现 (n-m)!的函数即可,注意溢出问题!

2、利用DFS,每个地方都有俩种可能,依次即可,记得带备忘录(缓存数据)-提高速度。

3、可知此题涉及子问题重叠,故而会想到DP算法,以下是实现。

dp[i][j] 表示从[0][0]到[i][j] 的所有路径之和。有以下转移方程:dp[i][j] = dp[i-1][j] + dp[i][j-1];

处理上述时,注意到 i = 0,j = 0需特殊处理!

   int uniquePaths(int m, int n) 
    {
        return count_paths(m,n);
    }
    
    int count_paths(int m,int n)
   {
	vector<vector<int>> dp(m,vector<int>(n,0));//dp[][]
	
	dp[0][0] = 1;
	for (int i = 1;i < n;i++)
	{
		dp[0][i] = 1;
	}

	for (int i = 1;i < m;i++)
	{
		dp[i][0] = 1;
	}

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

	return dp[m-1][n-1];
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值