diff --git a/Problem-1 b/Problem-1 new file mode 100644 index 00000000..57602e97 --- /dev/null +++ b/Problem-1 @@ -0,0 +1,33 @@ +// Time Complexity: O(2^(m+n)) +// Space Complexity: O(n) + +// Generate all possible combinations that start with the index +// Combinations are generated in a choose and not choose manner +// If chosen recursively call the function after reducing target value and add number to list +// If target becomes = 0 add to result list + +class Solution { + public List> combinationSum(int[] candidates, int target) { + List> result = new ArrayList<>(); + helper(candidates, target, 0, result, new ArrayList<>()); + return result; + } + + private void helper(int[] candidates, int target, int index, List> result, List list) { + if(target == 0) { + result.add(new ArrayList<>(list)); + return; + } + + if(target < 0) + return; + + for(int i = index; i < candidates.length; i++) { + if(candidates[i] <= target) { + list.add(candidates[i]); + helper(candidates, target - candidates[i], i, result, list); + list.remove(list.size()-1); + } + } + } +} \ No newline at end of file diff --git a/Problem-2 b/Problem-2 new file mode 100644 index 00000000..01aa7986 --- /dev/null +++ b/Problem-2 @@ -0,0 +1,60 @@ +// Time Complexity: O(4^n) +// Space Complexity: O(n) + +// Use recursion to create all possible ways to insert '+', '-', '*' in between numbers +// Keep track of the current calculated value and last used number for backtracking +// As '*' has more precedence backtrack the last used number and calculate again +// Add the expression to result list when the expression calculates to the traget value + +class Solution { + List result; + + public List addOperators(String num, int target) { + this.result = new ArrayList<>(); + helper(num, 0, 0l, 0l, new StringBuilder(), target); + return result; + } + + private void helper(String num, int index, Long calc, Long tail, StringBuilder path, int target) { + if(index == num.length()) { + // calculates value becomes equal to target + if(calc == target) { + result.add(path.toString()); + } + } + + for (int i = index; i < num.length(); i++) { + // if number has prefix 0 skip it + if(num.charAt(index) == '0' && i != index) + break; + + String s = num.substring(index, i + 1); + long curr = Long.parseLong(s); + int length = path.length(); + + // if it is the first number only add the number not any operators + if (index == 0) { + path.append(curr); + helper(num, i + 1, curr, curr, path, target); + path.setLength(length); + } + else { + // + operator + path.append("+").append(curr); + helper(num, i + 1, calc + curr, curr, path, target); + path.setLength(length); + + // - operator + path.append("-").append(curr); + helper(num, i + 1, calc - curr, -curr, path, target); + path.setLength(length); + + // * operator + path.append("*").append(curr); + helper(num, i + 1, calc - tail + (tail * curr), tail * curr, path, target); + path.setLength(length); + } + } + + } +} \ No newline at end of file