LeetCode Unique Paths

原题链接在这里:https://leetcode.com/problems/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?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

题解:

DP问题.需保存历史数据为走到当前格子的不同路径数,用二维数组dp保存。 

更新当前点dp[i][j]为上一行同列dp[i-1][j]的值 + 本行上一列dp[i][j-1]的值,因为走到上一行同列的值想走到当前格都是往下走一步,左边同理。

初始化是第一行和第一列都是1.

答案是dp[m-1][n-1].

Time Complexity: O(m*n). Space: O(m*n).

AC Java:

 1 public class Solution {
 2     public int uniquePaths(int m, int n) {
 3         if(m == 0 || n == 0){
 4             return 0;
 5         }
 6         int [][] dp = new int[m][n];
 7         for(int i = 0; i<m; i++){
 8             dp[i][0] = 1;
 9         }
10         for(int j = 0; j<n; j++){
11             dp[0][j] = 1;
12         }
13         for(int i = 1; i<m; i++){
14             for(int j = 1; j<n; j++){
15                 dp[i][j] = dp[i-1][j] + dp[i][j-1];
16             }
17         }
18         return dp[m-1][n-1];
19     }
20 }

存储历史信息可以用一维数组完成从而节省空间。生成一个长度为n的数组dp, 每次更新dp[j] += dp[j-1], dp[j-1]就是同行前一列的历史结果,dp[j]为更新前是同列上一行的结果,所以dp[j] += dp[j-1]就是更新后的结果。

Note:外层loop i 从0开始,dp[0] = 1, 相当于初始了第一列,所以i=0开始要初始第一行

Time Complexity: O(m*n). Space: O(n).

 

 1 class Solution {
 2     public int uniquePaths(int m, int n) {
 3         if(m == 0 || n == 0){
 4             return 0;
 5         }
 6         
 7         int [] dp = new int[n];
 8         for(int j = 0; j<n; j++){
 9             dp[j] = 1;
10         }
11         
12         for(int i = 1; i<m; i++){
13             for(int j = 1; j<n; j++){
14                 dp[j] = dp[j] + dp[j-1];
15             }
16         }
17         
18         return dp[n-1];
19     }
20 }

有进阶版题目Unique Paths II.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824960.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值