码迷,mamicode.com
首页 > 其他好文 > 详细

62.Unique Paths (法1递归-动态规划法2数学公式)

时间:2015-02-10 23:18:37      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:

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<iostream>
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");
}

62.Unique Paths (法1递归-动态规划法2数学公式)

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43707431

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!