<LeetCode OJ> 62. / 63. Unique Paths(I / II)

本文详细介绍了使用动态规划解决LeetCode中的唯一路径问题、唯一路径II问题及最小路径和问题,包括代码实现和时间空间复杂度分析。

62. Unique Paths

My Submissions
Total Accepted: 75227  Total Submissions: 214539  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Array Dynamic Programming
Show Similar Problems

分析:

思路首先:令从(1,1)到(m,n)的最大走法数为dp[m,n]
任何一个点都是从上面走下来和从右边走过来两种可能的和
显然dp[m,n]=dp[m-1,n]+dp[m,n-1]
最简单的动态规划问题...........时间复杂度O(M*N),空间复杂度O(M*N)

class Solution {  
public:  
    int uniquePaths(int m, int n) {  
        vector< vector<int> >  result(m+1);   
        for(int i=0;i <=m ;i++)   
                result[i].resize(n+1);//设置数组的大小m+1行,n+1列   
        for(int i=1;i<=n;i++)  
            result[1][i]=1;  
        for(int i=1;i<=m;i++)  
            result[i][1]=1;  
        for(int i=2;i<=m;i++)  
            for(int j=2;j<=n;j++)  
                result[i][j]=result[i-1][j]+result[i][j-1];  
        return result[m][n];  
    }  
};  




63. Unique Paths II

My Submissions
Total Accepted: 55136  Total Submissions: 191949  Difficulty: Medium

Follow up for "Unique Paths":紧接着上一题“唯一路劲”,现在考虑有一些障碍在网格中,无法到达,请重新计算到达目的地的路线数目

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]

The total number of unique paths is 2.

Note: m and n will be at most 100.

Subscribe to see which companies asked this question

Hide Tags
  Array Dynamic Programming
Hide Similar Problems
  (M) Unique Paths


分析:

思路首先:
此题与原问题相较,变得是什么?
1,此障碍物下面和右边将不在获得来自于此的数量,也可以理解为贡献为0
2,有障碍的地方也将无法到达(这一条开始时没想到,总感觉leetcode题目意思不愿意说得直接明了),也就是说此点的可到达路劲数直接为0

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m=obstacleGrid.size();
        int n=obstacleGrid[0].size();
        vector< vector<int> >  result(m+1);   
        for(int i=0;i <=m ;i++)   
            result[i].resize(n+1);//设置数组的大小m+1行,n+1列   
        //初始化一定要正确,否则错无赦    
        result[1][1]= obstacleGrid[0][0]==1? 0:1;    
        for(int i=2;i<=n;i++)  
            result[1][i]=obstacleGrid[0][i-1]==1?0:result[1][i-1];//由上一次来推到  
        for(int i=2;i<=m;i++)  
            result[i][1]=obstacleGrid[i-1][0]==1?0:result[i-1][1];  
            
        for(int i=2;i<=m;i++)  
            for(int j=2;j<=n;j++)  
                result[i][j]=obstacleGrid[i-1][j-1]==1?0:result[i-1][j]+result[i][j-1];  //一旦当前有石头就无法到达,直接置零
            
        return result[m][n];
    }
};




联动另外一个问题:

64. Minimum Path Sum

My Submissions
Total Accepted: 62294  Total Submissions: 183284  Difficulty: Medium

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Subscribe to see which companies asked this question

Hide Tags
  Array Dynamic Programming
Show Similar Problems

分析:

很显然的动态规划问题。

令从原点(1,1)到目的点(m,n)的最小路劲和为result[m,n] 
任何一个点的路劲和都是来自二维数组上一行的最小路劲和或者来自右一列的最小路劲和与当前位置的值相加的结果 显然result[m,n]=min(result[m-1,n]+grid[m,n],result[m,n-1]+grid[m,n]) 
注意初始化问题

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int row=grid.size();//行
        int col=grid[0].size();
        vector< vector<int> >  result(row);     
        for(int i=0;i <row ;i++)     
            result[i].resize(col,0);//设置数组的大小row行,col列 
        result[0][0]=grid[0][0];//初始化    
        for(int i=1;i<col;i++)//初始化第一行
            result[0][i]=result[0][i-1]+grid[0][i];
        for(int i=1;i<row;i++)//初始化第一列
            result[i][0]=result[i-1][0]+grid[i][0];
        for(int i=1;i<row;i++)//计算中间结果
            for(int j=1;j<col;j++)
                result[i][j]=min(result[i][j-1]+grid[i][j],result[i-1][j]+grid[i][j]);
        return result[row-1][col-1];
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50485468

原作者博客:http://blog.youkuaiyun.com/ebowtang

本博客LeetCode题解索引:http://blog.youkuaiyun.com/ebowtang/article/details/50668895

你提供的代码是 LeetCode 中 `uniquePaths` 问题的一个标准 **动态规划解法**,用于计算一个 `m x n` 网格中从左上角到右下角的不同路径数量,每次只能向右或向下移动一步。 你提到使用 **Visual Studio 2022 (VS2022)**,这说明你可能在本地开发环境中运行这段代码时遇到了一些问题,比如编译错误、运行时错误、或者对某些语法不理解。 --- ### ✅ 正确代码(适用于 VS2022): 确保你包含了必要的头文件 `<vector>`,并且使用了 `std` 命名空间。 ```cpp #include <vector> using namespace std; class Solution { public: int uniquePaths(int m, int n) { vector<vector<int>> f(m, vector<int>(n)); for (int i = 0; i < m; ++i) { f[i][0] = 1; } for (int j = 0; j < n; ++j) { f[0][j] = 1; } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { f[i][j] = f[i - 1][j] + f[i][j - 1]; } } return f[m - 1][n - 1]; } }; ``` --- ### 🧪 VS2022 中运行建议: 1. **确保项目类型为 C++ 项目**(如控制台应用、空项目等)。 2. **在 main 函数中测试代码**: ```cpp #include <iostream> int main() { Solution sol; cout << sol.uniquePaths(3, 7) << endl; // 示例输入 return 0; } ``` 3. **编译和运行**: - 使用快捷键 `Ctrl + Shift + B` 编译项目。 - 使用 `Ctrl + F5` 或点击“本地 Windows 调试器”运行程序。 --- ### ❗常见问题及解决方法: #### ✅ 问题 1:报错 `vector` 未声明? - **原因**:未包含 `<vector>` 头文件或未使用 `std` 命名空间。 - **解决方法**:加上 `#include <vector>` 和 `using namespace std;`。 #### ✅ 问题 2:编译错误 C2059: 语法错误? - **原因**:可能将代码直接粘贴到了不支持 C++ 的 `.c` 文件中。 - **解决方法**:确保文件后缀为 `.cpp`,并设置为 C++ 编译模式。 #### ✅ 问题 3:运行时报错 `LNK2019: 无法解析的外部符号`? - **原因**:没有 `main` 函数或未正确设置项目类型。 - **解决方法**:确保有 `main()` 函数,且项目是可执行项目(控制台应用)。 --- ### ✅ 代码逻辑简要说明: - 使用二维数组 `f` 来记录每个位置 `(i, j)` 的路径数。 - 初始化第一行和第一列为 1,因为只有一种方式到达。 - 动态规划递推公式:`f[i][j] = f[i-1][j] + f[i][j-1]`。 - 最终结果是右下角的值 `f[m-1][n-1]`。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值