我不明白,为什么完全相同的Python代码在Java中给出不同的结果。我的意思是,这两种语言的数组处理有什么不同吗?或者我在下面的代码中遗漏了什么。你知道吗
在以下代码中(即,尝试求解https://leetcode.com/problems/unique-paths/),java
在Python被拒绝时被接受。我检查了可能的失败案例:对于uniquePaths(7,3)
,Python返回结果7,而Java返回28(这是正确的答案)。你知道吗
我试着调试并找出导致差异的代码中任何可能的差异,但没有成功。你知道吗
有谁能为我的这种行为或我的实现中的任何错误提供一些见解吗?谢谢
**Java代码**:
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m+1][n+1];
return pathHelper(1,1,m, n, dp);
}
private int pathHelper(int loc_x, int loc_y, int m, int n, int[][] dp){
if(loc_x==m && loc_y==n)return 1;
if(loc_x >m || loc_y>n)return 0;
if(dp[loc_x][loc_y] != 0)return dp[loc_x][loc_y];
int count = pathHelper(loc_x + 1, loc_y, m, n, dp) + pathHelper(loc_x, loc_y+1, m, n, dp) ;
dp[loc_x][loc_y] = count;
return count;
}
}
Python代码:
class Solution(object):
def uniquePaths(self, m, n):
dp = [[0]*(n+1)]*(m+1)
return self.pathHelper(1,1,m, n, dp)
def pathHelper(self, loc_x, loc_y, m, n, dp):
if(loc_x==m and loc_y==n):
return 1
if(loc_x >m or loc_y>n):
return 0
if(dp[loc_x][loc_y] != 0):
return dp[loc_x][loc_y]
count = self.pathHelper(loc_x + 1, loc_y, m, n, dp) + self.pathHelper(loc_x, loc_y+1, m, n, dp)
dp[loc_x][loc_y] = count
return count
dp = [[0]*(n+1)]*(m+1)
不是在Python中定义2D列表的正确方法。改用这个:dp = [[0]*(n+1) for _ in range(m+1)]
相关问题 更多 >
编程相关推荐