1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/combination-sum-iv.java
Matej Focko f0cdb67ac1
chore(java): format
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-03-02 21:01:53 +01:00

35 lines
768 B
Java

import java.util.TreeMap;
class Solution {
private TreeMap<Integer, Integer> cache;
private int combinationSumRec(int[] nums, int target) {
if (target < 0) {
// Base: Target is below zero
return 0;
}
if (target == 0) {
// Base: We have found a possible combination
return 1;
}
if (cache.containsKey(target)) {
// Base: Target is already precomputed
return cache.get(target);
}
int combinations = 0;
for (int num : nums) {
combinations += combinationSumRec(nums, target - num);
}
cache.put(target, combinations);
return combinations;
}
public int combinationSum4(int[] nums, int target) {
cache = new TreeMap<>();
return combinationSumRec(nums, target);
}
}