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
57 changes: 57 additions & 0 deletions combination_sum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//Time Complexity - O(n*2 ^ (m+n))
//Space Complexity - O(n^2)
// class Solution {
// List<List<Integer>> result;
// public List<List<Integer>> combinationSum(int[] candidates, int target) {
// this.result= new ArrayList<>();
// helper(candidates,target,new ArrayList<>(),0);
// return result;
// }
// private void helper(int[] candidates,int target, List<Integer> path,int i){
// //base
// if(target==0) {
// result.add(new ArrayList<>(path));
// return;
// }
// if(target<0 || i==candidates.length) return;
// //logic
// //0
// helper(candidates,target,new ArrayList<>(path),i+1);
// //action
// path.add(candidates[i]);
// // System.out.println(path);
// //1
// //recurse
// helper(candidates,target-candidates[i],new ArrayList<>(path),i);
// }
// }

//Time Complexity - O(2 ^ (m+n))
//Space Complexity - O(n)
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.result= new ArrayList<>();
helper(candidates,target,new ArrayList<>(),0);
return result;
}
private void helper(int[] candidates,int target, List<Integer> path,int i){
//base
if(target==0) {
result.add(new ArrayList<>(path));
return;
}
if(target<0 || i==candidates.length) return;
//logic
//0
helper(candidates,target,path,i+1);
//action
path.add(candidates[i]);
// System.out.println(path);
//1
//recurse
helper(candidates,target-candidates[i],path,i);
//backtrack
path.remove(path.size()-1);
}
}
40 changes: 40 additions & 0 deletions expression_and_operator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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){
//base
if(pivot==num.length()) {
if(calc == target){
result.add(path.toString());
}
}
//logic
for(int i=pivot;i<num.length();i++){
if(num.charAt(pivot) == '0' && i != pivot) break; // preoccuring zero
long curr = Long.parseLong(num.substring(pivot,i+1));
int le = path.length(); // stack variable
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); // why - sign ??
path.setLength(le);
//*
path.append("*").append(curr);
helper(num,target,i+1,calc-tail+(tail*curr),tail*curr,path);
path.setLength(le);
}
}
}
}