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
33 changes: 33 additions & 0 deletions CombinationSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Time Complexity : O(2^(N))
// Space Complexity :O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
class Solution {
List<List<Integer>> res;

public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.res = new ArrayList<>();
// Arrays.sort(candidates);
helper(candidates, target, 0, new ArrayList<>());
return res;
}

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

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

for (int i = pivot; i < candidates.length; i++) {
if (target - candidates[i] < 0) {
continue;
}
path.add(candidates[i]);
if (target - candidates[i] >= 0)
helper(candidates, target - candidates[i], i, path);
path.remove(path.size() - 1);
}

}
}
54 changes: 54 additions & 0 deletions ExpressoionAddOp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Time Complexity : O(4^(N))
// Space Complexity :O(length of string)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no

class Solution {
List<String> result;

public List<String> addOperators(String num, int target) {
this.result = new ArrayList<>();
helper(num, 0, new StringBuilder(), 0, 0, target);
return result;
}

private void helper(String num, int pivot, StringBuilder path, long calc, long tail, int target) {
// base
if (pivot == num.length()) {
if (target == calc) {
result.add(path.toString());
}
}

for (int i = pivot; i < num.length(); i++) {
if (num.charAt(pivot) == '0' && pivot != i)
continue;

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

if (pivot == 0) {
int inl = path.length();
path.append(curr);
helper(num, i + 1, path, curr, curr, target);
path.setLength(inl);
} else {
int inl = path.length();

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

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

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