?LeetCode刷題實(shí)戰(zhàn)39:組合總和
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?組合總和,我們先來看題面:
https://leetcode-cn.com/problems/combination-sum
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
題意
樣例
示例?1:
輸入:candidates = [2,3,6,7], target = 7,
所求解集為:
[
??[7],
??[2,2,3]
]
示例?2:
輸入:candidates = [2,3,5], target = 8,
所求解集為:
[
? [2,2,2,2],
? [2,3,3],
? [3,5]
]
題解
回溯法
以 target = 7 為根結(jié)點(diǎn),每一個(gè)分支做減法。減到 0 或者負(fù)數(shù)的時(shí)候,剪枝。其中,減到 0 的時(shí)候結(jié)算,這里 “結(jié)算” 的意思是添加到結(jié)果集。

class?Solution?{
????public?List> combinationSum(int[] candidates, int?target) {
????????List> res = new?ArrayList<>();
????????Arrays.sort(candidates);
????????backtrack(candidates, target, res, 0, new?ArrayList());
????????return?res;
????}
????private?void?backtrack(int[] candidates, int?target, List> res,
) {
????????int?i, ArrayListtmp_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 < candidates[start]) break;
????????????tmp_list.add(candidates[start]);
????????????backtrack(candidates, target - candidates[start], res, start, tmp_list);
????????????tmp_list.remove(tmp_list.size() - 1);
????????}
????}
}
上期推文:
評(píng)論
圖片
表情
