<LeetCode OJ> 64. Minimum Path Sum

本文解析LeetCode上的三个动态规划题目:Minimum Path Sum、Unique Paths及Unique Paths II,提供详细的解题思路与代码实现。

64. Minimum Path Sum

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.


分析:

很显然的动态规划问题。

定义子问题:令从原点(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];
    }
};





联动另外两个问题:

62. Unique Paths

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.


分析:

定义子问题:令从原点(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

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.



分析:

此题与原问题相较,变得是什么?
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];  
    }  
}; 



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

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

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

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

<think>我们正在解决LeetCode题目时出现的NameError: Solution类未定义的问题。这个问题通常发生在尝试运行或测试TwoSum(两数之和)问题的解决方案时。 根据引用内容,我们有几个不同版本的TwoSum解决方案,但都是定义一个名为Solution的类,其中包含一个名为twoSum的方法。 错误信息"NameError: Solution class not defined"意味着在代码执行环境中,没有找到名为Solution的类。这可能是由于以下原因: 1. 代码没有正确包含Solution类的定义。 2. 代码存在语法错误,导致类定义失败。 3. 运行环境没有正确加载代码。 我们以引用[1]中的Python代码为例: ```python class Solution: def twoSum(self, nums, target): a = {} for i, v in enumerate(nums): if v in a: return a[v], i a[target - v] = i ``` 如果我们在运行这段代码之前没有定义Solution类,或者代码中有语法错误(比如缩进错误),就会导致这个错误。 解决步骤: 1. 确保在运行代码之前,已经完整定义了Solution类。例如,在LeetCode的在线编辑器中,我们只需要提交这个类,而不需要额外的代码(如创建实例和调用方法的代码)。 2. 在本地测试时,我们需要创建一个Solution类的实例,然后调用twoSum方法,并传入参数。但是,注意LeetCode要求我们只提交类,而不需要提交测试代码。如果我们在本地测试,需要自己编写测试代码。 例如,在本地测试时,我们可以这样写: ```python class Solution: def twoSum(self, nums, target): a = {} for i, v in enumerate(nums): if v in a: return [a[v], i] # 注意:LeetCode要求返回的是列表,所以这里最好返回列表 a[target - v] = i # 测试代码 if __name__ == '__main__': sol = Solution() print(sol.twoSum([2, 7, 11, 15], 9)) # 应该输出 [0,1] 或 [1,0]?注意:在代码中,我们返回的是先出现的数的索引和当前索引,而当前索引大于先出现的索引。对于[2,7],当遍历到7时,2已经在a中,所以返回a[2](即0)和当前索引1。 ``` 3. 注意代码缩进:在Python中,缩进非常重要,必须一致。通常使用4个空格。 4. 另外,注意方法名的大小写:twoSum,在Python中习惯使用下划线分隔(如two_sum),但LeetCode的题目要求方法名为twoSum,所以必须保持一致。 5. 如果是在LeetCode提交,确保没有额外的输出(如print语句)和多余的代码(如测试代码)。 6. 如果是在本地运行,确保保存了文件,并且运行的是包含Solution类定义的文件。 7. 如果使用Jupyter Notebook,确保已经运行了包含Solution类定义的单元格。 根据引用[5]的例子,输入是[2,7,11,15],目标值是9,返回[0,1](因为2+7=9,索引0和1)。 因此,遇到NameError时,请检查: - 是否正确定义了Solution类(包括正确的缩进)。 - 在需要实例化Solution类的地方,是否在定义之后(比如先定义类,再创建实例)。 - 是否有拼写错误(如将Solution拼错)。 如果问题仍然存在,请提供具体的代码和运行环境,以便进一步排查。 下面,我们根据引用[1]的Python代码,写一个完整的本地测试示例(注意:在LeetCode提交时,只需要提交Solution类,不需要提交测试部分):</think>### 解决 LeetCode "Solution类未定义" 的错误 在 LeetCode 上提交 TwoSum 解决方案时遇到 `NameError: Solution class not defined` 错误,通常由以下原因造成: #### 1. **代码结构错误**(最常见原因) LeetCode 要求严格遵循指定的类名和方法签名: ```python # 必须包含 Solution 类定义 class Solution: # ✅ 正确定义类 def twoSum(self, nums: List[int], target: int) -> List[int]: # ✅ 方法签名匹配 num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i ``` **错误示例**: ```python # ❌ 缺少类定义 def twoSum(nums, target): # 直接定义函数 # ...代码... ``` #### 2. **本地测试时的环境问题** 在本地运行需额外处理: ```python # 本地测试时需添加执行代码 class Solution: # ...twoSum方法... if __name__ == "__main__": sol = Solution() print(sol.twoSum([2, 7, 11, 15], 9)) # ✅ 创建实例调用方法 ``` #### 3. **语法错误导致类未定义** 常见语法问题: - 缩进错误(Python 严格要求4空格缩进) - 缺少冒号 `:` 在 `class Solution:` 和 `def twoSum(...):` 后 - 方法参数类型提示错误(如误用 `List` 而未导入) #### 4. **LeetCode 平台特殊要求** - 方法必须返回指定类型(如 `List[int]`) - 不可修改方法签名(参数名/顺序必须一致) - 不能添加额外输出(如 `print` 语句) ### 正确解决方案示例 ```python from typing import List # 类型提示需要导入 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {} for i, num in enumerate(nums): diff = target - num if diff in seen: return [seen[diff], i] seen[num] = i return [] # 确保所有路径有返回值 ``` ### 验证步骤 1. **检查类定义**:确认存在 `class Solution:` 2. **检查方法签名**:`def twoSum(self, nums: List[int], target: int) -> List[int]` 3. **本地测试**:在实例化后调用 `sol.twoSum(...)` 4. **提交代码**:删除所有测试代码后再提交 > 在 LeetCode 的代码编辑器中,只需提交 `Solution` 类(不含测试代码),平台会自动实例化并调用方法[^1][^2][^3]。 --- ### 相关问题 1. 如何正确处理 LeetCode 中的类型提示(如 `List[int]`)? 2. 为什么 LeetCode 的输入参数有时是 `self`,本地运行时却不需要? 3. 除了 `NameError`,还有哪些常见的 LeetCode 提交错误? 4. 如何为 TwoSum 问题设计有效的测试用例?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值