Problem: Combination Sum II
ANKUSH KUMAR
1 min read
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
((Note: The solution set must not contain duplicate combinations.))
class Solution {
public List < List < Integer >> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List < List < Integer >> result = new ArrayList();
find(result, candidates, target, 0, new ArrayList < Integer > ());
return result;
}
public void find(List < List < Integer >> result, int[] candidates, int target, int from, List < Integer > list) {
if (target == 0) {
result.add(new ArrayList < Integer > (list));
} else if (target > 0) {
for (int i = from; i < candidates.length && candidates[i] <= target; i++) {
if (i > from && candidates[i] == candidates[i - 1]) continue;
list.add(candidates[i]);
find(result, candidates, target - candidates[i], i + 1, list);
list.remove(list.size() - 1);
}
}
}
}
1
Subscribe to my newsletter
Read articles from ANKUSH KUMAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
ANKUSH KUMAR
ANKUSH KUMAR
({MERN Stack Developer at mackph}) | <Ex-Internshala Student Partner(ISP 16)> | <5 star coder at Hackerrank> | <Self employed at Mackph> | <GSSoC '22 Contributor> | <Ex-Campus Ambassador at International MUN>