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>}
};