这题就是不能重复取的题,首先要做的事情就是对数组进行排序。

    1. 需要额外提供一个数组 boolean[] visited 用以判断前面节点是否已获取,主要用于去重操作。
    2. 没有步骤 #1 的判断,那么当输入为 [1,1,2], target=3 时则会返回 [1,2]、[1,2] 重复元素,这就体现 boolean[] visited 的作用,用以剪枝去重。它的意思是,当两数相等时,前面重复的元素已经取得了,本轮就跳过。

      1. public class No_82_combinationSum2 {
      2. public static void main(String[] args) {
      3. No_82_combinationSum2 go = new No_82_combinationSum2();
      4. int[] nums = {1, 1, 2};
      5. int target = 3;
      6. List<List<Integer>> lists = go.combinationSum2(nums, target);
      7. for (List<Integer> list : lists) {
      8. System.out.println(list);
      9. }
      10. }
      11. List<List<Integer>> res;
      12. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
      13. if (candidates == null || candidates.length == 0 || target < 1) return new ArrayList<>();
      14. res = new ArrayList<>();
      15. Arrays.sort(candidates);
      16. boolean[] visited = new boolean[candidates.length];
      17. List<Integer> path = new ArrayList<>();
      18. backTracking(candidates, 0, target, path, visited);
      19. return res;
      20. }
      21. private void backTracking(int[] nums, int pos, int target, List<Integer> path, boolean[] visited) {
      22. if (target < 0) return;
      23. if (target == 0) {
      24. // collect
      25. res.add(new ArrayList<>(path));
      26. return;
      27. }
      28. for (int i = pos; i < nums.length; i++) {
      29. System.out.println(getBlackSpace(pos) + "当前节点: " + nums[i]);
      30. // #1
      31. // if (i > 0 && !visited[i - 1] && nums[i - 1] == nums[i]) continue;
      32. path.add(nums[i]);
      33. visited[i] = true;
      34. // 剪枝
      35. backTracking(nums, i + 1, target - nums[i], path, visited);
      36. path.remove(path.size() - 1);
      37. visited[i] = false;
      38. }
      39. }
      40. private String getBlackSpace(int n) {
      41. StringBuilder sb = new StringBuilder();
      42. for (int i = 0; i < 2 * n; i++) {
      43. sb.append(" ");
      44. }
      45. return sb.toString();
      46. }
      47. }