leetcode39. 组合总和(回溯)
生活随笔
收集整理的這篇文章主要介紹了
leetcode39. 组合总和(回溯)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)無重復(fù)元素的數(shù)組 candidates 和一個(gè)目標(biāo)數(shù) target ,找出 candidates 中所有可以使數(shù)字和為 target 的組合。
candidates 中的數(shù)字可以無限制重復(fù)被選取。
說明:
所有數(shù)字(包括 target)都是正整數(shù)。
解集不能包含重復(fù)的組合。
示例 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);//回溯}} }總結(jié)
以上是生活随笔為你收集整理的leetcode39. 组合总和(回溯)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode47. 全排列 II(回
- 下一篇: leetcode216. 组合总和 II