给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
    candidates 中的每个数字在每个组合中只能使用一次。
    说明:
    所有数字(包括目标数)都是正整数。
    解集不能包含重复的组合。
    示例 1:
    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    所求解集为:
    [
    [1, 7],
    [1, 2, 5],
    [2, 6],
    [1, 1, 6]
    ]
    示例 2:
    输入: candidates = [2,5,2,1,2], target = 5,
    所求解集为:
    [
    [1,2,2],
    [5]
    ]
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum-ii


    思路:
    上一题的升级版?给定的数组元素允许重复了,上一题没有重复,上一题可以重复利用,这题不能重复利用
    基本都一样,不多说了,盘他

    1. class Solution {
    2. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    3. //记录最终的返回值
    4. List<List<Integer>> res = new LinkedList<>();
    5. //记录当前的路径
    6. Deque<Integer> path = new ArrayDeque<Integer>();
    7. int len = candidates.length;
    8. Arrays.sort(candidates);
    9. boolean [] isVisited = new boolean[len];
    10. dfs(len,target,0,isVisited,res,path,candidates);
    11. return res;
    12. }
    13. private void dfs(int len, int target, int first, boolean[] isVisited, List<List<Integer>> res, Deque<Integer> path, int[] candidates) {
    14. if (target == 0){
    15. res.add(new ArrayList<>(path));
    16. return;
    17. }
    18. for (int i = first; i < len; i++) {
    19. if (i != 0 && candidates[i] == candidates[i - 1] && !isVisited[i - 1]) {
    20. continue; // 防止重复
    21. }
    22. if (target < candidates[i]){
    23. continue;
    24. }
    25. if (isVisited[i]){
    26. continue;
    27. }
    28. path.add(candidates[i]);
    29. isVisited[i] = true;
    30. dfs(len, target - candidates[i], i, isVisited, res, path, candidates);
    31. isVisited[i] = false;
    32. path.remove(candidates[i]);
    33. }
    34. }
    35. }

    好像确实难了一点