LeetCode62 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?
题目的意思是:在一个m*n 个方块格子里面, 机器人位置为[1,1], 目标点为[m,n], 问一共有多少条独立路径让机器人走到目标点
看到题目可以得出对于位置[i,j], 路径数P[i,j]=P[i-1,j]+P[i,j-1], 所以可以根据该公式写出一个递归的求解思路,如下:
void uniquePaths_helper(int &re, int m, int n, int m_now, int n_now)
{
if(m_now==m&&n_now==n)
{
re++;
}
if(m<m_now||n<n_now)
{
return ;
}
if(m>m_now)
{
//uniquePaths_helper(re, m, n, ++m_now, n_now);
//错误,相当于把m_now在该递归中前相加
uniquePaths_helper(re, m, n, m_now+1, n_now);
}
if(n>n_now)
{
//uniquePaths_helper(re, m, n, m_now, ++n_now);
uniquePaths_helper(re, m, n, m_now, n_now+1);
}
}
int uniquePaths(int m, int n)// time exceed
{
int result=0;
int m_now=1;
int n_now=1;
uniquePaths_helper(result, m, n, m_now, n_now);
return result;
}
这种做法虽然能够得出正确结果,但超出了时间限制。
注:这里我写递归的时候,直接使用前置++,导致算法一直无法得到正确结果,即m_now 在递归前的时候一直自增,后面debug的时候才发现,自己还是要多多学习才好。
还有一种方法是用动态规划的思想,推导公式我们已经有了,即P[i,j]=P[i-1,j]+P[i,j-1], 即我们可以非常快的得出到位置[i,j]的路径数,所以可以通过遍历第i行得到走到该位置的路径数。
int uniquePaths2(int m, int n)
{
vector<int> res(n,0);
res[0]=1;
for(int i=0;i<m;i++)
{
for(int j=1;j<n;j++)
{
res[j]+=res[j-1];
}
}
return res[n-1];
}
这里[0,0]表示[1,1]的位置,由于第[i,j]的路径只跟[i-1,j]和[i,j-1]有关,所以可以直接把上一行的数据保存下来,即对于第i行来说,P[i,j]=P[i-1,j], 而P[i,0]恰好等于P[i-1,0]。故进行不停相加即可得到P[i,j]。