Combination Sum (Java)

来源:互联网 发布:张家口 知乎 编辑:程序博客网 时间:2024/06/05 15:49

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] 

注意,但凡不出现重复[2,2,3] [3,2,2]这种情况,都要设一个i的start传入递归。 这道题的解决方法和题目subset以及combinations类似。

Source

public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>> st = new ArrayList<List<Integer>>();        List<Integer> a = new ArrayList<Integer>();    if(candidates.length == 0) return st;    int sum = 0;    int start = 0;        Arrays.sort(candidates);  //这道题的测试数据有乱序的    dfs(start, sum, candidates, target, st, a);    return st;    }    public void dfs(int start, int sum, int[] candidates, int target, List<List<Integer>> st, List<Integer> a){    if(sum > target) return;    if(sum == target){    st.add(new ArrayList<Integer>(a));    return;    }        for(int i = start; i < candidates.length; i++){    a.add(candidates[i]);    dfs(i, sum + candidates[i], candidates, target, st, a); //注意sum是要随着dfs变化的    a.remove(a.size() - 1);    }    }}


Test

    public static void main(String[] args){    int[] candidates = {2,3,6,7};    int target = 7;    System.out.println(new Solution().combinationSum(candidates, target));        }



0 0
原创粉丝点击