給定一個無重復元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的數字可以無限制重復被選取。
說明:
所有數字(包括 target)都是正整數。
解集不能包含重復的組合。
示例 1:
輸入:candidates = [2,3,6,7], target = 7,
所求解集為:
[
[7],
[2,2,3]
]
代碼
class Solution {List<List<Integer>> cList=new ArrayList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {combinationS(candidates,target,new ArrayList<>());return cList;}public void combinationS(int[] candidates, int target,List<Integer> temp) {if(target==0)//找到滿足條件的序列{cList.add(new ArrayList<>(temp));return;}for(int i=0;i<candidates.length;i++){if(target<candidates[i]||temp.size()>0&&candidates[i]<temp.get(temp.size()-1))continue;//通過篩選升序的序列去重temp.add(candidates[i]);combinationS(candidates,target-candidates[i],temp);temp.remove(temp.size()-1);//回溯}}
}