Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CombinationSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.*;

//O(2 ^ (m+n)) time where m is the candidates length and n is the target
// O(n) space
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
helper(candidates, 0, target, ans, new ArrayList<>());
return ans;
}

private void helper(int[] candidates, int i, int target, List<List<Integer>> ans, List<Integer> path) {
if (i == candidates.length || target < 0) return;

if (target == 0) {
ans.add(new ArrayList<>(path));
return;
}

//choose i
path.add(candidates[i]);
helper(candidates, i, target-candidates[i], ans, path);

//backtrack
path.remove(path.size()-1);

//skip i
helper(candidates, i+1, target, ans, path);
}
}
60 changes: 60 additions & 0 deletions ExpressionAddOperators.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.*;

// Iterative recursion O(4^n) time, O(n) space
class Solution {
List<String> ans;
public List<String> addOperators(String num, int target) {
// calc tail
// + calc + curr + curr
// - calc - curr - curr
// * (calc - tail) + (tail * curr) tail * curr

ans = new ArrayList<>();
helper(num, target, 0, new StringBuilder(), 0, 0);
return ans;
}

private void helper(String num, int target, int pivot, StringBuilder path, long calc, long tail) {

if (pivot == num.length()) {
if (calc == target) {
ans.add(path.toString());
}
return;
}

for (int i = pivot; i < num.length(); i++) {

if (num.charAt(pivot) == '0' && i != pivot) { // dont continue from here since leading zeros
break;
}

long curr = Long.parseLong(num.substring(pivot, i+1)); // generate each string and convert to long

int len = path.length();

if (pivot == 0) { // first level, no operators

path.append(curr);
helper(num, target, i+1, path, curr, curr); // path+curr converts num to string path
path.setLength(len);
}
else {
// +
path.append("+").append(curr);
helper(num, target, i+1, path, calc + curr, curr);
path.setLength(len);

// -
path.append("-").append(curr);
helper(num, target, i+1, path, calc - curr, -curr);
path.setLength(len);

// *
path.append("*").append(curr);
helper(num, target, i+1, path, calc - tail + (tail * curr), tail * curr);
path.setLength(len);
}
}
}
}