1. class Solution {
  2. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  3. // sorting the candidates to avoid duplicated during recursion
  4. Arrays.sort(candidates);
  5. List<List<Integer>> result = new ArrayList<>();
  6. List<Integer> temp = new ArrayList<>();
  7.  
  8. findCombinationSumWithoutDuplicates(candidates, target, 0, result, temp);
  9. return result;
  10. }
  11.  
  12.  
  13. public void findCombinationSumWithoutDuplicates(int[] nums, int target, int index, List<List<Integer>> result, List<Integer> temp)
  14. {
  15. // Base condition 1: when target becomes 0
  16. if(target == 0)
  17. {
  18. result.add(new ArrayList<>(temp));
  19. return;
  20. }
  21.  
  22. // Base condition 2: when we reach end of the array
  23. if(index == nums.length)
  24. return;
  25.  
  26.  
  27. // pick the element
  28. if(nums[index] <= target)
  29. {
  30. temp.add(nums[index]);
  31. // i+1 because each number used once
  32. findCombinationSumWithoutDuplicates(nums, target - nums[index], index+1, result, temp);
  33.  
  34. // do not pick the element
  35. temp.remove(temp.size() - 1);
  36. }
  37.  
  38. // skip the duplicates
  39. while(index+1 < nums.length && nums[index] == nums[index+1])
  40. index++;
  41.  
  42. findCombinationSumWithoutDuplicates(nums, target, index+1, result, temp);
  43. return;
  44. }
  45. }