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
62 changes: 62 additions & 0 deletions ExpressionAddOperators.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//package Backtracking-1;

import java.util.*;

public class ExpressionAddOperators {
List<String> res;
private List<String> solution(String num, int target){
this.res = new ArrayList<>();
helper(num, 0, 0l, 0l, "", target);
return res;
}

private void helper(String num, int pivot, long calc , long tail, String path , int target){

//base
if(pivot == num.length()){
if(calc == target) {
res.add(path);
}
return;
}


//logic
for(int i = pivot; i< num.length();i++){
//preceeding 0
if(num.charAt(pivot)=='0' && i>pivot){
continue;
}

//what if > 10 digits
long cur = Long.parseLong(num.substring(pivot, i+1));
if(pivot==0){
helper(num, i+1, cur, cur, path+cur, target);
}
else{

//recurse
//+
helper(num, i+1, calc + cur, cur, path + "+" + cur, target);


//-
helper(num, i+1, calc - cur, -cur, path + "-" + cur, target);

//*
helper(num, i+1, calc - tail + tail * cur, tail * cur, path + "*" + cur, target);
}
}
}

public static void main(String[] args){
String num = "123";
int target = 6;
ExpressionAddOperators solver = new ExpressionAddOperators();
List<String> res = solver.solution(num, target);
System.out.println("List = "+ res);

}


}
35 changes: 35 additions & 0 deletions SumOfProductsSubarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//package Backtracking-1;

public class SumOfProductsSubarray {
long sum;
long prod;
boolean choose;
private long calSumOfProducts(int[] nums){
this.sum = 0;
this.prod = 1;
this.choose = true;
helper(nums, 0, prod, choose);
return sum;
}

private void helper(int[] nums, int idX, long prod, boolean choose){

//base
if(idX == nums.length) return;

//logic
prod*=nums[idX];
System.out.println("prod = " + prod);
helper(nums, idX+1, sum + prod, true);
helper(nums, idX+1, prod, false);

}

public static void main(String[] args){
int[] nums = {2,3,6,7};
SumOfProductsSubarray solution = new SumOfProductsSubarray();
long res = solution.calSumOfProducts(nums);
System.out.println("Sum of product of all sub arrays = " + res);
}

}