알고리즘 : 조합 다시 네 개의 조합 합계 II II의 총 수

설명

地址: https://leetcode.com/problems/combination-sum-ii/
후보 번호 (후보)과 대상 번호 (대상)의 컬렉션을 감안할 때, 후보의 모든 고유 한 조합을 찾을 경우 대상 후보 숫자의 합계.

후보자의 각 숫자 만 조합하면 사용할 수있다.

노트 :

(대상 포함) 모든 숫자는 양의 정수가 될 것입니다.
이 솔루션 세트는 중복 조합을 포함 할 수 없습니다.
예 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]
]

예 2 :

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

솔루션

해결 방법 :

  1. 오름차순으로 배열 보내기
  2. (어느 쪽이 선택하거나 선택하지) 후 향적 방법으로.
  3. target == 0큐에 추가 할 때 (복제 방식을 마지막 개체가 비어 있기 때문에, 객체는, 인덱스 방법이 될 수 없습니다).
  4. if (i > start && candidates[i] == candidates[i - 1])이 상태를 해결하기 위해 특별 판사, 첫 번째 숫자는 이전과 같을 수 없습니다 나타내며, 예를 들어, 두 개의 1가, 다음 [1, 2, 5], [1,7]두 가지가있을 것입니다. 먼저 다음 두 번째는 2로 시작하는 것, (1)에서 시작합니다. 당신은 법을 디버깅을 찾을 수 있어야합니다.
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);
      }
    }
  }
}

다운로드

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

게시 된 127 개 원래 기사 · 원 찬양 12 ·은 20000 +를 볼

추천

출처blog.csdn.net/zgpeace/article/details/103780722