首页 > 其他 > 详细

LeetCode | Unique Path

时间:2015-03-26 17:39:41      阅读:239      评论: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. 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?

思路:

/*
从左上到右下 只能下或者有 总共有多少种方法。这是一个典型的DP问题,这里记录的遍历dp[i][j]为从左上到达{i,j} 这个位置可能的方法总数,
那么对于dp[i+1][j+1] = dp[i][j+1] + dp[i+1[j];
当然对于边界需要特殊考虑 ,同时需要注意的就是在申请二维空间时  必须让申请的空间比给出的多一个。
*/

int Unique_path(int m,int n)
{
	vector<vector<int> > dp(m+1);
	int i,j;
	for(i=0;i<dp.size();i++)
		dp[i].assign(n+1,0);
	dp[0][0] =1;
	for(i=0;i<dp.size();i++)
	{
		for(j=0;j<dp[0].size();j++)
		{
			if(i!=0 || j!=0)
			{
				if(i==0)
					dp[i][j] = dp[i][j-1];
				else if(j == 0) 
					dp[i][j] = dp[i-1][j];
				else
					dp[i][j] = dp[i][j-1] + dp[i-1][j];
			}
			
		}
	}		
	return dp[m][n];
}
int main()
{
	cout<<Unique_path(3,7)<<endl;
	
	return 0;
}


LeetCode | Unique Path

原文:http://blog.csdn.net/yusiguyuan/article/details/44652253

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!