[LeetCode]Combination Sum

题目描述

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] 

从候选值列表中,给出和为目标值的集合列表,候选值可以多次选择。


解题思路


我首先想到的是递归,因此可能方法不是最优的,但是这是一种解决问题的途径,具体步骤:
  1. 将目标数组按从小到大的顺序进行排序;
  2. 如果目标值小于候选值的第一个,则返回;
  3. 从候选值数组的边界往0循环,如果当前的candidates[index]==target,则将target添加到列表中,如果candidates[index]<=target,则以target-candidates[index]为子目标值循环步骤2、3得到子列表,然后将candidates[index]添加到子列表的每一个集合中;
  4. 最终得到结果列表。

代码


public static List<List<Integer>> combinationSum(int[] candidates, int target) {
    	//从小到大排序
    	Arrays.sort(candidates);
    	return getCombination(candidates,candidates.length - 1 ,target);
    }

递归求解函数
/**
     * 递归求解函数
     * @param candidates
     * @param bound
     * @param target
     * @return
     */
    public static List<List<Integer>> getCombination(int[] candidates, int bound,int target) {
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	
    	if(target < candidates[0]){
    		return result;
    	}
    	
    	for(int i = bound ;i >=0;i--){
        	if(candidates[i]==target){
        		//如果侯选值等于目标值,则添加到list中
        		List<Integer> list = new ArrayList<Integer>();
        		list.add(candidates[i]);
        		result.add(list);
        	} else if(candidates[i] < target){
        		//如果候选值小于目标值,则递归求解,需要注意下次求解的起点应该从candidates[i]往前
        		List<List<Integer>> tempList = getCombination(candidates, i,target - candidates[i]);
        		if(tempList.size()!=0){
        			for(List<Integer> list:tempList){
        				list.add(candidates[i]);
        				result.add(list);
        			}
        		}
        	}	
        }
    	
    	return result;
    }


你可能感兴趣的:([LeetCode]Combination Sum)