【发布时间】:2020-06-01 19:12:21
【问题描述】:
我目前正在做LeetCode's Robber Question。我通过了 68/69 个测试用例,唯一失败的测试用例如下:像这样 [0, 0, 0, 0, 0 .....] 的数组满或零。您能否向我解释如何修复我的代码以修复此错误?另外,如果您对优化有任何建议,请告诉我!我的代码:
class Solution {
public int rob(int[] nums) {
if (nums.length == 0 ) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int[] memo = new int[nums.length];
return Math.max(dp(0, nums, memo), dp(1, nums, memo));
}
public int dp(int index, int[] nums, int[] memo) {
int max;
if (memo[index] != 0) {
return memo[index];
}
if (index == nums.length - 1 || index == nums.length - 2) {
max = nums[index];
} else if (index == nums.length - 3) {
max = nums[index] + nums[nums.length - 1];
}
else {
max = Math.max(nums[index] + dp(index + 2, nums, memo), nums[index] + dp(index + 3, nums, memo));
}
memo[index] = max;
return max;
}
}
【问题讨论】: