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
64 changes: 64 additions & 0 deletions 282. Expression Add Operators/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
class Solution {
public List<String> addOperators(String num, int target) {

List<String> result = new ArrayList();

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

return result;

}

public void helper(String num, int target, long calc, long tail, int pivot, StringBuilder path,
List<String> result) {

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

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

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

long cur = Long.parseLong(num.substring(pivot, i + 1)); // substring take +1 address to strip

int length = path.length();

if (pivot == 0) {

path.append(cur);

helper(num, target, cur, cur, i + 1, path, result);

path.setLength(length);

} else {

//+
path.append("+").append(cur);
helper(num, target, calc + cur, cur, i + 1, path, result);
path.setLength(length);

//-
path.append("-").append(cur);
helper(num, target, calc - cur, -cur, i + 1, path, result);
path.setLength(length);

//*
path.append("*").append(cur);
helper(num, target, calc - tail + tail * cur, tail * cur, i + 1, path, result);
path.setLength(length);

}
}
}
}

// TC - 4*n
// SC - O(n)
40 changes: 40 additions & 0 deletions 39. Combination Sum/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {

List<List<Integer>> result = new ArrayList<>();

helper(target, candidates, result, 0, new ArrayList<>());

return result;

}

public void helper(int target, int[] candidates, List<List<Integer>> result, int pivot, List<Integer> path){

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

if(target < 0 || pivot == candidates.length){
return;
}


//for loop base recursion
for(int i = pivot; i < candidates.length; i++){

path.add(candidates[i]);

helper(target - candidates[i], candidates, result, i, path);

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

}
}
}

// TC - O(2^(m+n))
// SC - O(n^2)