Skip to content
Open

Solved #1101

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
25 changes: 25 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if (candidates == null || candidates.length == 0) return new ArrayList<>();

result = new ArrayList<>();

backtrack(candidates, target, 0, 0, new ArrayList<>());

return result;
}

public void backtrack(int[] candidates, int target, int index, int currSum, List<Integer> combination) {
if (currSum == target) {
result.add(new ArrayList<>(combination));
return;
}
if (currSum > target || index == candidates.length) return;

combination.add(candidates[index]);
backtrack(candidates, target, index, currSum + candidates[index], combination);
combination.removeLast();
backtrack(candidates, target, index + 1, currSum, combination);
}
}
42 changes: 42 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution {
List<String> result;
public List<String> addOperators(String num, int target) {
if (num == null || num.length() == 0) return new ArrayList<>();

result = new ArrayList<>();

backtrack(num, target, 0, 0, 0, "");

return result;
}

public void backtrack(String num, int target, int index, long calc, long tail, String exp) {

if (index == num.length()) {
if (target == calc) result.add(exp);
return;
}

for (int i=index; i<num.length(); i++) {

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

// if it is not a single digit number and the first digit is 0 then we should skip this iteration

if (index != i && num.charAt(index) == '0') break;

if (index == 0) {
// 1st digit or number
backtrack(num, target, i + 1, calc + curr, curr, curr + "");
} else {
// + operator
backtrack(num, target, i + 1, calc + curr, curr, exp + "+" + curr);
// - operator
backtrack(num, target, i + 1, calc - curr, -curr, exp + "-" + curr);
// * operator
backtrack(num, target, i + 1, (calc-tail) + (tail*curr), tail*curr, exp + "*" + curr);
}
}

}
}