Algorithm: Combination back four the total number of combinations Sum II II

Explanation

地址:https://leetcode.com/problems/combination-sum-ii/
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

solution

Solutions:

  1. Give an array in ascending order,
  2. (Either choose, or not choose) with a retrospective way.
  3. When target == 0when added to the queue (a clone manner, the object can not be indexed manner, because the last objects are empty).
  4. if (i > start && candidates[i] == candidates[i - 1])Special judge to resolve this condition, represents the first digit can not be the same as before, for example, there are two 1, then [1, 2, 5], [1,7], there will be two. First start at 1, then the second would begin with 2. You should be able to find debugging law.
package backtracking;

import java.util.*;

// https://leetcode.com/problems/combination-sum-ii/
public class CombinationSumII {

  public static void main(String[] args) {
    CombinationSumII obj = new CombinationSumII();
    int[] candidates = {10,1,2,7,6,1,5};
    int target = 8;
    List<List<Integer>> resultList = obj.combinationSum2(candidates, target);
    System.out.println("resultList >> " + Arrays.toString(resultList.toArray()));
  }

  public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    List<List<Integer>> resultList = new ArrayList<>();
    Arrays.sort(candidates);
    recursive(candidates, target, resultList, new ArrayList<Integer>(), 0);

    return resultList;
  }

  public void recursive(int[] candidates, int target, List<List<Integer>> resultList, List<Integer> list, int start) {
    if (target == 0) {
      List<Integer> newList = new ArrayList<Integer>(list);

      resultList.add(newList);
    } else if (target > 0) {
      for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
      // remove duplicate
        if (i > start && candidates[i] == candidates[i - 1]) {
          continue;
        }
        list.add(candidates[i]);
        recursive(candidates, target - candidates[i], resultList, list, i + 1);
        list.remove(list.size() - 1);
      }
    }
  }
}

Download

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/CombinationSumII.java

Published 127 original articles · won praise 12 · views 20000 +

Guess you like

Origin blog.csdn.net/zgpeace/article/details/103780722