Combination Sum

来源:互联网 发布:java常用包和类 编辑:程序博客网 时间:2024/04/27 17:25

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] 

思路:也是采用组合的思想,每选出一个数candidates[i],还需要选择的数字的和应该为target-candidates[i],若没有选择当前的这个数字candidates[i],那么还需要选择的数字的和依然为target。

public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        Arrays.sort(candidates);        List<List<Integer>> res =new ArrayList<List<Integer>>();     select_sum(candidates,0,target,new ArrayList<Integer>(),res);     return res;    }    //从candidates中选出数字使得所选出数字的和为target,temp作为所选出数字的临时栈,idx代表candidates的下标public  void select_sum(int[] candidates, int idx, int target,List<Integer> temp, List<List<Integer>> res) { //如果超过了target就返回if (target<0)return;//如果target,说明所选出数字的和为target,就将temp添加到res中if (target==0) {List<Integer> temp_new = new ArrayList<Integer>(temp);if(temp_new.size()==0) return;res.add(temp_new);return;}if (idx >= candidates.length)return;//如果当前数字被选中,由于数字可以重复被选,所以下标还是从idx开始选择,target变成target-candidates[idx]temp.add(candidates[idx]);select_sum(candidates, idx, target-candidates[idx], temp, res);//如果当前数字没有被选中,那就从下一个数字开始选择temp.remove(temp.size() - 1);select_sum(candidates, idx + 1, target, temp, res);}}


0 0
原创粉丝点击