40. 조성물 합 II
후보와 번호를 하나의 목표 대상의 배열을 감안할 때, 당신은 목표 숫자와 조합에 대한 모든 후보를 찾을 수 있습니다.
각 숫자 후보는 각 조합에서 한 번만 사용.
설명 :
(대상 번호를 포함하여) 모든 수치는 양의 정수이다.
솔루션 세트는 그 중복 조합을 포함 할 수 없습니다.
예 1 :
입력 : 후보 = 10,1,2,7,6,1,5]이 대상 = 8이
설정이 해결된다 :
[
[1, 7],
[1,2,5],
[2, 6]
[1, 1,6]
]
실시 예 2 :
입력 : 후보 = 2,5,2,1,2]이 대상 = 5,
세트가 해결된다 :
[
[1,2,2-],
[5]
]
출처 : 숙박 버튼 (LeetCode)
링크 : HTTPS : //leetcode-cn.com/problems/combination-sum-ii는
모든 네트워크에서 공제 저작권. 상업 무단 전재 소스를 표시하시기 바랍니다 승인 된 공식, 비상업적 재판에 문의하시기 바랍니다.
추신 : 더 이상의 이상에없는 반복에있다
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
backtrack(candidates, 0, target, res, new ArrayList<Integer>());
return res;
}
private void backtrack(int [] candidates, int start, int target, List<List<Integer>> res, ArrayList<Integer> tmp) {
if (target == 0) {
res.add(new ArrayList(tmp));
return;
}
for (int i = start; i < candidates.length; i ++) {
if (i > start && candidates[i] == candidates[i-1]) continue;
if (target - candidates[i] >= 0) {
tmp.add(candidates[i]);
backtrack(candidates, i + 1, target - candidates[i], res, tmp);
tmp.remove(tmp.size() - 1);
} else {
break;
}
}
}
}