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
31 changes: 31 additions & 0 deletions Problem70.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time Complexity : O(2 ^ (m+n)) where m is the candidates length and n is the target
// Space Complexity : O(n)

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
helper(candidates, target, 0, new ArrayList<>(), result);
return result;
}

private void helper(int[] candidates, int target, int pivot, List<Integer> path, List<List<Integer>> result) {
//base
if (target < 0 || candidates.length == pivot) {
return;
}

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

for (int i = pivot; i < candidates.length; i++) {
//action
path.add(candidates[i]);
//recurse
helper(candidates, target - candidates[i], i, path, result);
//backtrack
path.remove(path.size() - 1);
}
}
}
55 changes: 55 additions & 0 deletions Problem71.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Time Complexity : O(4^n)
// Space Complexity : O(n)

class Solution {
List<String> result;
public List<String> addOperators(String num, int target) {

this.result = new ArrayList<>();

helper(num, target, 0, 0, 0, new StringBuilder());

return result;
}

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

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

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

if(num.charAt(pivot) == '0' && i != pivot) break;

long curr = Long.parseLong(num.substring(pivot, i+1));

int le = path.length();

if(pivot == 0){
path.append(curr);
helper(num, target, i+1, curr, curr, path);
path.setLength(le);

}else{

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

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

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