標籤:leetcode java combination sum
題目:
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
題意:
給定一組整數(C)和一個目標值 (T),從(C)中找出所有的存在且唯一的組合,使他們的和等於(T)。
同一個重複數字可以在C無限次的選擇。
注意:
1.所有的數字包括目標值都是非負整數.
2. 組合中的元素(a1, a2, … , ak)為升序排列。(ie, a1 ≤ a2 ≤ … ≤ ak).
3.最終的解中組合不能出現重複.
比如,給定一組整數集2,3,6,7 和目標值7,
一個解集為:
[7]
[2, 2, 3] .
演算法分析:
該題是一個求解迴圈子問題的題目,採用遞迴進行深度優先搜尋。基本思路是先排好序,然後每次遞迴中把剩下的元素一一加到結果集合中,並且把目標減去加入的元素,然後把剩下元素(包括當前加入的元素)放到下一層遞迴中解決子問題。演算法複雜度因為是NP問題,所以自然是指數量級的。
AC代碼:
/** * The first impression of this problem should be depth-first search(DFS). To solve DFS problem, recursion is a normal implementation. * Note that the candidates array is not sorted, we need to sort it first. */public class Solution { List<List<Integer>> result;List<Integer> solu;public List<List<Integer>> combinationSum(int[] candidates, int target) { result = new ArrayList<>(); solu = new ArrayList<>(); if(candidates == null || candidates.length == 0) return result; Arrays.sort(candidates); getCombination(candidates, target, 0, 0); return result; }public void getCombination(int[] candidates, int target, int sum, int level){if(sum>target) return;if(sum==target){result.add(new ArrayList<>(solu));return;}for(int i=level;i<candidates.length;i++){sum+=candidates[i];solu.add(candidates[i]);getCombination(candidates, target, sum, i);solu.remove(solu.size()-1);sum-=candidates[i];}}}
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Combination Sum