Combination Sum 組合數求和-Leetcode
阿新 • • 發佈:2022-05-04
原題:
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 (a
- 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]
題意是找到所有加起來和為target值的組合,候選數可以重複使用。這明顯是一道利用回溯的題目,可以想象成深度搜索。
以題目給出的【2,3,6,7】為例。一棵樹根節點有四個子節點(2,3,6,7)。每個子節點下又有不小於本子節點的所有子節點。
public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); solve(candidates,0,target,new LinkedList<Integer>()); return ans; } private List<List<Integer>> ans=new LinkedList<>(); private void solve(int[] candidates,int start,int target,LinkedList<Integer> current){ if (target==0){ ans.add(copy(current)); return; } if (target<candidates[start]){ return; } else { for (int iterator=start;iterator<candidates.length;iterator++){ if (candidates[iterator]>target){ break; } current.add(candidates[iterator]); solve(candidates, iterator, target - candidates[iterator], current); current.pollLast(); } return; } } private LinkedList<Integer> copy(LinkedList<Integer> source){ LinkedList<Integer> dest=new LinkedList<>(); for (int i:source){ dest.add(i); } return dest; } }
另一個效率更高的演算法,逆向思維。
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
return combinationSum(candidates, target, 0);
}
public List<List<Integer>> combinationSum(int[] candidates, int target, int start) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
for (int i = start; i < candidates.length; i++) {
if (candidates[i] <target) {
for (List<Integer> ar : combinationSum(candidates, target - candidates[i], i)) {
ar.add(0, candidates[i]);
res.add(ar);
}
} else if (candidates[i] == target) {
List<Integer> lst = new ArrayList<>();
lst.add(candidates[i]);
res.add(lst);
} else
break;
}
return res;
}
}