把下面的代码转成javaclass Solution(object): def coinChange(self, coins, amount): self.cache = {} def helper(coins, curAmount): if curAmount in self.cache: return self.cache[curAmount] globalMin = amount + 1 if curAmount == 0: return 0 if curAmount < 0: return amount + 1 for coin in coins: curMin = helper(coins, curAmount - coin) if curMin == globalMin: continue globalMin = min(curMin + 1, globalMin) self.cache[curAmount] = globalMin return globalMin result = helper(coins, amount) return -1 if result == amount + 1 else result
时间: 2024-02-10 13:09:46 浏览: 176
这段代码是 Python 代码,将其转化为 Java 代码后,可以得到如下的代码:
```
public class Solution {
private Map<Integer, Integer> cache = new HashMap<>();
public int coinChange(int[] coins, int amount) {
int result = helper(coins, amount);
return result == amount + 1 ? -1 : result;
}
private int helper(int[] coins, int curAmount) {
if (cache.containsKey(curAmount)) {
return cache.get(curAmount);
}
int globalMin = amount + 1;
if (curAmount == 0) {
return 0;
}
if (curAmount < 0) {
return amount + 1;
}
for (int coin : coins) {
int curMin = helper(coins, curAmount - coin);
if (curMin == globalMin) {
continue;
}
globalMin = Math.min(curMin + 1, globalMin);
}
cache.put(curAmount, globalMin);
return globalMin;
}
}
```
这段 Java 代码与原来的 Python 代码功能相同,它采用了递归加缓存的方式来解决硬币兑换问题。具体来说,它将原来的 `cache` 字典替换成了 `cache` 哈希表,使用了 Java 语言自带的 `Map` 类来实现。此外,Java 代码中的列表表示方式也与 Python 代码稍有不同,需要使用数组来代替。最后,Java 代码中的条件语句、循环语句等基本语法结构与 Python 代码也存在一些细微的差异,需要注意语法的转化。
阅读全文