(java)leetcode-39

1840 ワード

Combination Sum
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]
    ]
    
        :
                         ,        ,       。
    (1)         ,  ,      target ,    list ,     list     ,             ,          。
    (2)           list  ,  target          target。
    (3)  (1)      ,       target/2 ,    list 。
    (4)      == target ,   list ,   list   result 。
    
    
    public class Solution {
        private List> result = new ArrayList>();
    	public List> combinationSum(int[] candidates, int target) 
    	{
    		Arrays.sort(candidates);
    		findanswer(0,new ArrayList(),candidates,target);
            return result;
        }
    	public void findanswer(int index,Listans,int[] candidates,int target)
    	{
    		while(index < candidates.length && candidates[index]<= target)
    		{
    		    //    ,   target
    			if(candidates[index] <= target/2)
    			{
    				List l1 = new ArrayList(ans);
    				l1.add(candidates[index]);
    				findanswer(index,l1,candidates,target-candidates[index]);
    			}
    			//       ,  list,    result 
    			if(candidates[index] == target)
    			{
    				List l1 = new ArrayList(ans);
    				l1.add(candidates[index]);
    				result.add(l1);
    			}
    			index++;
    		}
    	}
    }