From 9dc591147a610764a10020c5a6ff7245f2c83eb1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 5 Aug 2022 11:06:37 +0200 Subject: [PATCH] problems: add combination sum IV Signed-off-by: Matej Focko --- problems/combination-sum-iv.java | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 problems/combination-sum-iv.java diff --git a/problems/combination-sum-iv.java b/problems/combination-sum-iv.java new file mode 100644 index 0000000..fc4de1e --- /dev/null +++ b/problems/combination-sum-iv.java @@ -0,0 +1,35 @@ +import java.util.TreeMap; + +class Solution { + private TreeMap 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); + } +}