DFS处理,有两个比较坑的要求:
- 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
,
若给定[7,6,3,2] ,target=7 ,顺序搜索可能出现[3,2,2],不满足要求1,所以可以先给数组升序排列。
onstack法搜索所有的可能会导致同时出现[2,2,3]、[3,2,2]这样的解,没有顺序?就加顺序
限制下次递归调用使用的index必须比当前的大,即是规定顺序。
public class Solution {
List<List<Integer>> retlist = new ArrayList<>(512);
public List<List<Integer>> combinationSum(int[] candidates, int target)
{
Arrays.sort(candidates);
dfs(candidates, target, 0, -1, new ArrayList<Integer>());
return retlist;
}
public void dfs(int[] arr, int t, int sum, int lastindex,ArrayList<Integer> arraylist)
{
if (sum > t)
return;
if (sum == t)
{
retlist.add(new ArrayList<>(arraylist));
return;
}
for (int i = 0; i < arr.length; i++)
{
if (i >= lastindex)
{
arraylist.add(arr[i]);
dfs(arr, t, sum + arr[i], i, arraylist);
arraylist.remove(arraylist.size()-1);
}
}
}
}