How to Calculate all Unique Combinations of a Target using Backtracking in Java
The challenge
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Constraints:
1 <= candidates.length <= 301 <= candidates[i] <= 200- All elements of
candidatesare distinct. 1 <= target <= 500
The solution in Java code
This problem is perform for using a backtracking algorithm to solve it.
geeksforgeeks.org
Using this technique, we can write the following code to solve our challenge:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// create a return variable
List<List<Integer>> res = new ArrayList<>();
// use backtracking to attempt to solve
// we will pass the following:
back(res,
new ArrayList<>(), // - return variable
target, // - the target number
candidates, // - all candidates
0 // - where we should start
);
// return our answer
return res;
}
// our backtracking helper method
private void back(List<List<Integer>> res,
List<Integer> tmp,
int remains,
int[] nums,
int start) {
// if our target is less than 0, get out
if (remains<0) return;
// if the remaining target is 0, return the target
if (remains==0) {
res.add(new ArrayList<>(tmp));
return;
}
// loop through all candidates
for (int i=start; i<nums.length; i++) {
// add each one
tmp.add(nums[i]);
// perform another round of backtracking
back(res,
tmp,
remains-nums[i],
nums,
i
);
// remove the last item
tmp.remove(tmp.size()-1);
}
}
}