[leetcode] 39. Combination Sum

来源:互联网 发布:国服mac版魔兽世界 编辑:程序博客网 时间:2024/06/07 08:02

题目:

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]]

题解:

像这种结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,如果仔细研究这些题目发现都是一个套路,都是需要另写一个递归函数,这里我们新加入三个变量,start记录当前的递归到的下标,list为一个解,lists保存所有已经得到的解,每次调用新的递归函数时,此时的target要减去当前数组的的数,

    public List<List<Integer>> combinationSum(int []candidates,int target){    List<List<Integer>> lists=new ArrayList<List<Integer>>();    List<Integer> list=new ArrayList<Integer>();    Arrays.sort(candidates);    getCombination(candidates,target,0,list,lists);    return lists;    }    public void getCombination(int[] candidates,int target,int start,List<Integer> list,List<List<Integer>> lists){    if(target<0)    return;    if(target==0){    //lists.add(list);  如果用该方法将其加入lists,则结果为空    lists.add(new ArrayList<Integer>(list));    return;    }    for(int i=start;i<candidates.length;i++){    list.add(candidates[i]);    getCombination(candidates,target-candidates[i],i,list,lists);    list.remove(list.size()-1);    }    }


原创粉丝点击