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
42 changes: 42 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.ArrayList;
import java.util.List;

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

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

//actual

//choose
List<Integer> np = new ArrayList(path);
np.add(candidates[idx]);
helper(candidates,target-candidates[idx],np,idx);
// path.remove(path.size()-1);

//not choose
helper(candidates,target,path,idx+1);



}

}

//time complexity: O(N^(T/M +1)) where N is the number of candidates, T is the target, and M is the minimum value in candidates.
//space complexity: O(T/M) for the recursion stack and the path list.
60 changes: 60 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.ArrayList;
import java.util.List;\

class Problem2 {
List<String> result;

public List<String> addOperators(String num, int target) {
result = new ArrayList<>();
if (num == null || num.length() == 0) return result;

helper(num, target, 0, 0, 0, "");
return result;
}

private void helper(String num, int target, int idx, long eval, long prev, String path) {
// base case
if (idx == num.length()) {
if (eval == target) {
result.add(path);
}
return;
}

// choose numbers of different lengths
for (int i = idx; i < num.length(); i++) {

// avoid leading zero numbers like "05"
if (i != idx && num.charAt(idx) == '0') break;

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

// first number (no operator)
if (idx == 0) {
helper(num, target, i + 1, curr, curr, path + curr);
} else {
// +
helper(num, target, i + 1,
eval + curr,
curr,
path + "+" + curr);

// -
helper(num, target, i + 1,
eval - curr,
-curr,
path + "-" + curr);

// *
helper(num, target, i + 1,
eval - prev + prev * curr,
prev * curr,
path + "*" + curr);
}
}
}
}

//time complexity: O(N * 4^N) where N is the length of the input string num.
//space complexity: O(N) for the recursion stack and the path string.