Combination Sum

来源:互联网 发布:白金数据剧情 编辑:程序博客网 时间:2024/04/30 23:48

题目原型:

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 (a1a2, … , 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] 

基本思路:

这题比较简单,明显的递归回溯,只要保证下一层的开始元素是这一层的结束元素即可。

ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates,int target){if (candidates == null || candidates.length == 0)return list;if (target < 0)return list;//排序数组Arrays.sort(candidates);combinationSum(candidates, target, new ArrayList<Integer>(), 0);return list;}public void combinationSum(int[] candidates, int target,ArrayList<Integer> num, int startIndex){if (target < 0)return;if (target == 0){list.add(new ArrayList<Integer>(num));return;}for (int i = startIndex; i < candidates.length; i++){num.add(candidates[i]);combinationSum(candidates, target - candidates[i], num, i);num.remove(num.size() - 1);//必须移除,否则影响下一步}}



0 0