LeetCode第62题:不同路径(中等)
- 题目:一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。问总共有多少条不同的路径?
- 思路一:想要把它变成一道数学问题来做,但是m=10,n=10的时候,阶乘的结果就大于整型最大值了,但是Python好像就可以。
class Solution {
public int uniquePaths(int m, int n) {
int ans=0;
if(m==0 || n==0 ) return ans;
int a = JC(m + n - 2);
int b = JC(m-1);
int c = JC(n-1);
ans=a/(b*c);
return ans;
}
public int JC(int n){
int ans=1;
for(int i=1;i<=n;i++){
ans*=i;
}
return ans;
}
}
- 思路二:思路来自于第22题生成括号的问题,但是发现递归就好像没执行一样。我分析,是因为整型不可以这么用。遂多加了一个字符串行的参数,大部分例子都可以通过,但是有些例子还是超出了时间限制。
这个是改之前的代码。
class Solution {
public int uniquePaths(int m, int n) {
int ans = 0;
if(m==0 || n==0 ) return ans;
int R = m-1;
int D = n-1;
ans = Path(R,D,ans);
return ans;
}
public int Path(int R,int D,int ans){
if(R==0 && D==0){
ans++;
return ans;
}
if(R>0){
Path(R-1,D,ans);
}
if(D>0){
Path(R,D-1,ans);
}
return ans;
}
}
这个是增加字符串参数后的代码。
class Solution {
public int uniquePaths(int m, int n) {
List<String> ans1=new ArrayList<>();
int ans = 0;
if(m==0 || n==0 ) return ans;
int R = m-1;
int D = n-1;
ans1 = Path(R,D,"",ans1);
ans=ans1.size();
return ans;
}
public List<String> Path(int R,int D,String s,List<String> ans1){
if(R==0 && D==0){
ans1.add(s);
return ans1;
}
if(R>0){
Path(R-1,D,s+"a",ans1);
}
if(D>0){
Path(R,D-1,s+"b",ans1);
}
return ans1;
}
}
- 思路三:动态方程 dp[i][j]=dp[i-1][j]+dp[i][j-1]比较巧妙。
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < n; i++) dp[0][i] = 1;
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}
作者:powcai
链接:https://leetcode-cn.com/problems/unique-paths/solution/dong-tai-gui-hua-by-powcai-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
优化一:将二维数组压缩为一维,想要算出当前位置只需要上一行数据和左边的数据即可。
class Solution {
public int uniquePaths(int m, int n) {
int[] pre = new int[n];
int[] cur = new int[n];
Arrays.fill(pre, 1);
Arrays.fill(cur,1);
for (int i = 1; i < m;i++){
for (int j = 1; j < n; j++){
cur[j] = cur[j-1] + pre[j];
}
pre = cur.clone();
}
return pre[n-1];
}
}
作者:powcai
链接:https://leetcode-cn.com/problems/unique-paths/solution/dong-tai-gui-hua-by-powcai-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
优化二:在优化一的基础上,两行变为一行,未更新前的结果就是上一行的结果。
class Solution {
public int uniquePaths(int m, int n) {
int[] cur = new int[n];
Arrays.fill(cur,1);
for (int i = 1; i < m;i++){
for (int j = 1; j < n; j++){
cur[j] += cur[j-1] ;
}
}
return cur[n-1];
}
}
作者:powcai
链接:https://leetcode-cn.com/problems/unique-paths/solution/dong-tai-gui-hua-by-powcai-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。