39.和の組み合わせ
非反復配列要素の候補と目標数の目標を考えると、あなたはそのターゲット番号との組み合わせのためのすべての候補者を見つけることができます。
候補者の無制限番号が繰り返され、選択することができます。
説明:
(ターゲットを含む)すべての数値は正の整数です。
ソリューションセットは、その重複した組み合わせを含めることはできません。
例1:
入力:候補= [2,3,6,7-]、目標 = 7は、
セットが解決される:
[
[7]、
[2,2,3-]
]
例2:
入力:候補= [2,3,5]、目標 = 8は、
セットが解決される:
[
[2,2,2,2]、
[2,3,3]、
[3,5]
]
出典:滞在ボタン(LeetCode)
リンクします。https://leetcode-cn.com/problems/combination-sum
すべてのネットワークからの控除が著作権を保有。商業転載は、ソースを明記してください許可公式、非商用の転載をご連絡ください。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
//System.out.println(candidates);
backtrack(candidates, target, res, 0, new ArrayList<Integer>());
return res;
}
private void backtrack(int[] candidates, int target, List<List<Integer>> res, int i, ArrayList<Integer> tmp_list) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(tmp_list));
return;
}
for (int start = i; start < candidates.length; start++) {
if (target < 0) break;
//System.out.println(start);
tmp_list.add(candidates[start]);
//System.out.println(tmp_list);
backtrack(candidates, target - candidates[start], res, start, tmp_list);
tmp_list.remove(tmp_list.size() - 1);
}
}
}