39. Combination Sum

来源:互联网 发布:阿里巴巴农村淘宝兰西 编辑:程序博客网 时间:2024/06/16 22:17

Given a set of candidate numbers (C(without duplicates) 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.
  • 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]]

public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        Arrays.sort(candidates);List<List<Integer>> data = new ArrayList<>();helper(data, new ArrayList<Integer>(), candidates, target, 0);return data;    }    public void helper(List<List<Integer>> data, List<Integer> temp, int[] candidates, int target, int index) {for (int i = index; i < candidates.length; ++i) {if (target > candidates[i]) {List<Integer> next = new ArrayList<>(temp);next.add(candidates[i]);helper(data, next, candidates, target - candidates[i], i);} else if (target == candidates[i]) {List<Integer> next = new ArrayList<>(temp);next.add(candidates[i]);data.add(next);break;} else {break;}}}}


原创粉丝点击