【发布时间】:2021-04-28 01:18:15
【问题描述】:
我正在解决 leetcode (#377) 上的组合 sum IV,内容如下: “给定一个包含所有正数且没有重复的整数数组,找出加起来为正整数目标的可能组合数。”
我使用带有记忆数组的自顶向下递归方法在 Java 中解决了这个问题:
public int combinationSum4(int[] nums, int target){
int[] memo = new int[target+1];
for(int i = 1; i < target+1; i++) {
memo[i] = -1;
}
memo[0] = 1;
return topDownCalc(nums, target, memo);
}
public static int topDownCalc(int[] nums, int target, int[] memo) {
if (memo[target] >= 0) {
return memo[target];
}
int tot = 0;
for(int num : nums) {
if(target - num >= 0) {
tot += topDownCalc(nums, target - num, memo);
}
}
memo[target] = tot;
return tot;
}
然后我认为我通过初始化整个备忘录数组来浪费时间并且可以只使用 Map 代替(这也将节省空间/内存)。于是我将代码改写如下:
public int combinationSum4(int[] nums, int target) {
Map<Integer, Integer> memo = new HashMap<Integer, Integer>();
memo.put(0, 1);
return topDownMapCalc(nums, target, memo);
}
public static int topDownMapCalc(int[] nums, int target, Map<Integer, Integer> memo) {
if (memo.containsKey(target)) {
return memo.get(target);
}
int tot = 0;
for(int num : nums) {
if(target - num >= 0) {
tot += topDownMapCalc(nums, target - num, memo);
}
}
memo.put(target, tot);
return tot;
}
不过我很困惑,因为在提交了我的代码的第二个版本之后,Leetcode 说它比第一个代码更慢并且占用的空间更多。 HashMap如何使用更多空间和运行速度比一个数组谁的值都必须初始化并且谁的长度大于HashMaps的大小?
【问题讨论】:
-
有一个提示:int 和 Integer。您正在使用的地图正在使用自动装箱。您应该尝试使用 Eclipse Collection 中的专用地图(例如):eclipse.org/collections/javadoc/8.0.0/org/eclipse/collections/…
-
这是一个很好的问题,顺便问一下,你做得很好。积分!
标签: java memoization