Easy to understand, java solution


  • 0
    K
    public class CombinationSumII {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        	Arrays.sort(candidates);
            return findCom(candidates, target, 0);
        }
        private List<List<Integer>> findCom(int[] candidates, int target, int start){
            List<List<Integer>> res = new LinkedList<>();
            for(int i = start; i < candidates.length; i++){
                if(start != i && candidates[i] == candidates[i - 1]){ 
                    continue;              //   this is to skip the duplicate nums, very simple!
                }
                else if(candidates[i] < target){
                    for(List<Integer> ar : findCom(candidates, target - candidates[i], start + 1)){
                        ar.add(0, i);
                        res.add(ar);
                    }
                }else if(candidates[i] == target){
                    List<Integer> l0 = new LinkedList<>();
                    l0.add(candidates[i]);
                    res.add(l0);
                }else{
                    break;
                }
            }
            return res;
        }
    }

  • 0
    Y

    I don't think you can simply skip the duplicate numbers. Consider [1,1] and target 2.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.