题:
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, 找出所有的满足条件的组合:使得组合里面的数字之和等于T,并且一些数字可以从C中午先选择。
分析:
深度优先搜索(DFS)是搜索算法的一种。最早接触DFS应该是在二叉树的遍历里面,二叉树的先序、中序和后序遍历实际上都属于深度优先遍历,实质就是深度优先搜索,后来在图的深度优先遍历中则看到了更纯正的深度优先搜索算法。
通常,我们将回溯法和DFS等同看待,可以用一个等式表示它们的关系:回溯法=DFS+剪枝。所以回溯法是DFS的延伸,其目的在于通过剪枝使得在深度优先搜索过程中如果满足了回溯条件不必找到叶子节点,就截断这一条路径,从而加速DFS。实际上,即使没有剪枝,DFS在从下层回退到上层的时候也是一个回溯的过程,通常这个时候某些变量的状态。DFS通常用递归的形式实现比较直观,也可以用非递归,但通常需要借组辅助的数据结构(比如栈)来存储搜索路径。
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<>();
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];
}
}
}