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
38 changes: 38 additions & 0 deletions CombinationSumBackTrack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//Time Complexity: 2 power (m+n)
//Space Compexity: O(m+n) + O(n)
//For primitive data type in result instead of exact path (list of integers etc.) we can use DP else use Backtracking for optimal solution

//Back Tracking
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.result = new ArrayList<>();
if(candidates == null || candidates.length == 0) return result;
helper(candidates, 0, target, new ArrayList<>());
return result;
}

private void helper(int[] candidates, int i, int target, List<Integer> path)
{
//Base case
if(target < 0 || i == candidates.length){
return;
}

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

//case 0
helper(candidates, i+1, target, path);

//case 1
path.add(candidates[i]);
helper(candidates, i, target-candidates[i], path);

//backtrack
path.remove(path.size() - 1); // remove last element added
}
}
46 changes: 46 additions & 0 deletions ExpressionAddOperators.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//Time Complexity : O(4 power n)
//Space Complexity: O(h)
class Solution {
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, String path, long calc, long tail, int index)
{
//base case
if(index == num.length()){
if(target == calc){
result.add(path);
return;
}
}
//logic

for(int i = index; i < num.length(); i++)
{
if(num.charAt(index) =='0' && index != i)
{
continue;
}
long curr = Long.parseLong(num.substring(index, i+1));
if(index == 0){
helper(num, target, path + curr, curr, curr, i+1);
}
else
{
// + case
helper(num, target, path + "+" + curr, calc + curr, curr, i+1);

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

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