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
51 changes: 51 additions & 0 deletions addOperators.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Time Complexity : O(4^n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None

class Solution {
List<String> result;
public List<String> addOperators(String num, int target) {
this.result = new ArrayList<>();

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

return result;
}

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

if(i == num.length()) {
if(calc == target && curr == 0) {
result.add(path.toString());
}
return;
}

curr = curr * 10 + num.charAt(i) - '0';

if(curr > 0) {
helper(num, target, i + 1, curr, calc, tail, path);
}

int le = path.length();

if(path.length() == 0) {
path.append(curr);
helper(num, target, i + 1, 0, curr, curr, path);
path.setLength(le);
} else {
path.append("+").append(curr);
helper(num, target, i + 1, 0, calc + curr, curr, path);
path.setLength(le);

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

path.append("*").append(curr);
helper(num, target, i + 1, 0, calc - tail + (tail * curr), tail * curr, path);
path.setLength(le);
}
}
}
32 changes: 32 additions & 0 deletions combinationSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Time Complexity : O(n * 2^(m+n)
// Space Complexity : O(n * h) -> O(n^2)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : None
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.result = new ArrayList<>();
helper(candidates, target, 0, new ArrayList<>());
return result;
}

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

//base case
if (target < 0) return;

if (target == 0) {
result.add(path);
return;
}

for (int i = pivot; i < candidates.length; i++) {
//action
List<Integer> list = new ArrayList<>(path);
list.add(candidates[i]);

//recurse
helper(candidates, target - candidates[i], i, list);
}
}
}