Leetcode——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?


这个题要写起来很简单,就那10行左右,关键是怎么去想这个问题。

其实之前写出来的是递归,但是毫无意外超时。

Leetcode中好多都是,不过也是,这也说明了,递归比较消耗资源。

专门把这道题拿上来是因为,其实这个题之前面试过了,但还是给忘了。

以此提醒自己一下,勿眼高手低!

这个图想我想到了另一道题,给定一个N*M的矩形,这个矩形中包含多少个矩形?有兴趣的可以想想。

本道题的代码如下:

class Solution {
public:
<span style="white-space:pre">	</span>int uniquePaths(int m, int n) {
	<span style="white-space:pre">	</span>int* mem=new int[m*n]();
	<span style="white-space:pre">	</span>for(int i=0; i<n; i++)
		<span style="white-space:pre">	</span>mem[i*m]=1;
	<span style="white-space:pre">	</span>for(int j=0; j<m; j++)
		<span style="white-space:pre">	</span>mem[j]=1;
	<span style="white-space:pre">	</span>for(int i=1; i<n; i++)
		<span style="white-space:pre">	</span>for(int j=1; j<m; j++)
			<span style="white-space:pre">	</span>mem[i*m+j]=mem[(i-1)*m+j]+mem[i*m+j-1];
			
	<span style="white-space:pre">	</span>return mem[n*m-1];
<span style="white-space:pre">	</span>}
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值