package leetcode;

import java.util.*;

/**
 * https://leetcode.com/problems/combination-sum-ii/
 */
public class Problem40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        List<Integer> candidateList = new ArrayList();
        for (int candidate : candidates) {
            candidateList.add(candidate);
        }
        List<Integer> accu = new ArrayList<>();
        combination(candidateList, target, 0, 0, accu, result);
        return result;
    }

    private void combination(List<Integer> candidateList, int target, int idx, int sum,
                             List<Integer> accu, List<List<Integer>> result) {
        if (sum == target) {
            result.add(accu);
            return;
        }
        if (sum > target) {
            return;
        }
        for (int i = idx; i < candidateList.size(); i++) {
            List<Integer> newList = candidateList.subList(i, candidateList.size());
            List<Integer> newAccu = new ArrayList<>(accu);
            int val = candidateList.get(i);
            newAccu.add(val);
            combination(newList, target, idx+1, sum+val, newAccu, result);

        }
    }

    public static void main(String[] args) {
        Problem40 prob = new Problem40();
        List<List<Integer>> result = prob.combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
        for (List<Integer> list : result) {
            System.out.println(list);
        }
    }
}

@@ -29,17 +29,121 @@
 va.util.
-*
+ArrayList;%0Aimport java.util.Arrays;%0Aimport java.util.HashSet;%0Aimport java.util.List;%0Aimport java.util.Set
 ;%0A%0A/**%0A 
@@ -581,32 +581,88 @@
  ArrayList%3C%3E();%0A
+        Set%3CList%3CInteger%3E%3E tmpResult = new HashSet%3C%3E();%0A
         combinat
@@ -696,25 +696,62 @@
 0, 0, accu, 
-r
+tmpResult);%0A        result.addAll(tmpR
 esult);%0A    
@@ -913,19 +913,18 @@
 %3E accu, 
-Lis
+Se
 t%3CList%3CI
@@ -1152,92 +1152,8 @@
 ) %7B%0A
-            List%3CInteger%3E newList = candidateList.subList(i, candidateList.size());%0A
     
@@ -1305,19 +1305,25 @@
 ination(
-new
+candidate
 List, ta
@@ -1329,18 +1329,16 @@
 arget, i
-dx
 +1, sum+
@@ -1363,290 +1363,8 @@
 lt);
-%0A%0A        %7D%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem40 prob = new Problem40();%0A        List%3CList%3CInteger%3E%3E result = prob.combinationSum2(new int%5B%5D%7B10, 1, 2, 7, 6, 1, 5%7D, 8);%0A        for (List%3CInteger%3E list : result) %7B%0A            System.out.println(list);
 %0A   

Solve problem 40