diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..db073d23 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,42 @@ +import java.util.ArrayList; +import java.util.List; + +class Problem1 { + List> result; + int s; + public List> combinationSum(int[] candidates, int target) { + s= candidates.length; + result = new ArrayList<>(); + helper(candidates,target,new ArrayList<>(),0); + return result; + } + + private void helper(int[] candidates, int target,List path,int idx){ + //base + if(target==0){ + result.add(path); + return; + } + if(target<0 || idx >=s){ + return; + } + + //actual + + //choose + List np = new ArrayList(path); + np.add(candidates[idx]); + helper(candidates,target-candidates[idx],np,idx); + // path.remove(path.size()-1); + + //not choose + helper(candidates,target,path,idx+1); + + + + } + +} + +//time complexity: O(N^(T/M +1)) where N is the number of candidates, T is the target, and M is the minimum value in candidates. +//space complexity: O(T/M) for the recursion stack and the path list. \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..d5016569 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,60 @@ +import java.util.ArrayList; +import java.util.List;\ + +class Problem2 { + List result; + + public List addOperators(String num, int target) { + result = new ArrayList<>(); + if (num == null || num.length() == 0) return result; + + helper(num, target, 0, 0, 0, ""); + return result; + } + + private void helper(String num, int target, int idx, long eval, long prev, String path) { + // base case + if (idx == num.length()) { + if (eval == target) { + result.add(path); + } + return; + } + + // choose numbers of different lengths + for (int i = idx; i < num.length(); i++) { + + // avoid leading zero numbers like "05" + if (i != idx && num.charAt(idx) == '0') break; + + long curr = Long.parseLong(num.substring(idx, i + 1)); + + // first number (no operator) + if (idx == 0) { + helper(num, target, i + 1, curr, curr, path + curr); + } else { + // + + helper(num, target, i + 1, + eval + curr, + curr, + path + "+" + curr); + + // - + helper(num, target, i + 1, + eval - curr, + -curr, + path + "-" + curr); + + // * + helper(num, target, i + 1, + eval - prev + prev * curr, + prev * curr, + path + "*" + curr); + } + } + } +} + +//time complexity: O(N * 4^N) where N is the length of the input string num. +//space complexity: O(N) for the recursion stack and the path string. +