39. Combination Sum

来源:互联网 发布:淘宝点击率 编辑:程序博客网 时间:2024/05/16 19:13

题目:Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums toT.

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,

思路:

1. 空集
2. 数组先排序


代码:

public class Solution {List<List<Integer>> ret=new ArrayList<List<Integer>>();List<Integer> tmp=new ArrayList<Integer>(); //链表一定要new出对象,否则只是引用    public List<List<Integer>> combinationSum(int[] candidates, int target) {        if(candidates == null) return null;    Arrays.sort(candidates);        DFS(0,0,target,candidates);    return ret;    }        void DFS(int start,int sum,int target,int[] candidates)    {    if(sum==target)     {    ret.add(new ArrayList<>(tmp)); //添加的时候,一定要用tmp链表重新new一下,否则没有数据    return;    }    else if(sum> target ) return;    else    {    for(int i=start ;i < candidates.length;i++)    {    tmp.add(candidates[i]);//添加数据    DFS( i, sum+candidates[i],target,candidates);    tmp.remove(tmp.size()-1); //remove 是用index去掉数据    }    }    }}



0 0