leetcode------Combination Sum

标题: Combination Sum
通过率: 27.7%
难度: 中等

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 (a1, a2, … , 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] 

本题依然是递归算法,算法的关键点是递归时重复元素。题目上说可以从candidate中重复一个元素,那么再递归时不用从i+1开始,还是从i开始,结果还可能是重复的情况,那么还是要res。cantain一次,具体细节看代码:

 1 public class Solution {

 2     public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {

 3         ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();

 4         ArrayList<Integer> tmp=new ArrayList<Integer>();

 5         Arrays.sort(candidates);

 6         dfs(candidates,target,0,res,tmp);

 7         return res;

 8     }

 9     public void dfs(int[] candidates, int target,int start,ArrayList<ArrayList<Integer>> res,ArrayList<Integer> tmp){

10         if(target<0)return;

11         if(target==0 && !res.contains(tmp)){

12             res.add(new ArrayList<Integer>(tmp));

13             return ;

14         }

15         for(int i=start;i<candidates.length;i++){

16             tmp.add(candidates[i]);

17             dfs(candidates,target-candidates[i],i,res,tmp);

18             tmp.remove(tmp.size()-1);

19         }

20     }

21 }

 

你可能感兴趣的:(LeetCode)