设为首页 加入收藏

TOP

Unique Paths (法1递归-动态规划法2数学公式)
2015-07-20 17:18:19 来源: 作者: 【 】 浏览:5
Tags: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. Therobot 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 willbe at most 100.

HideTags

Array Dynamic Programming

?

?

?

#pragma once
#include
  
   
using namespace std;

//法1:递归,超时
int uniquePaths1(int m, int n) 
{
	if (m == 2 || n == 2)
		return m+n-2;
	return uniquePaths1(m - 1, n) + uniquePaths1(m, n - 1);

}

//法2:数学公式 求m+n-2中取m-1的组合数
int uniquePaths2(int m, int n)
{
	long long result = 1;
	int reduce = m - 1;
	for (int i = m - 1; i >= 1; i--)
	{
		result *= (n - 1 + i);
		while (reduce>0 && result%reduce == 0)
		{
			result = result / reduce;
			reduce--;
		}
	}
	//内层循环用while后,由于最后结果一定是能整除的,所以不用再加以下
	/*while (reduce > 0)
	{
		result = result / reduce;
	}*/
	return result;
}


void main()
{
	cout << uniquePaths2(36, 7) << endl;
	cout << uniquePaths1(36, 7) << endl;
	system("pause");
}

  

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode Merge k Sorted Lists 下一篇POJ 1734 Sightseeing trip (Floy..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·有没有哪些高效的c++ (2025-12-27 08:20:57)
·Socket 编程时 Accep (2025-12-27 08:20:54)
·计算机网络知识点总 (2025-12-27 08:20:52)
·一篇说人话的文章, (2025-12-27 07:50:09)
·Python Web框架哪家 (2025-12-27 07:50:06)