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

 

 从数组中找出和为target的组合,每个元素可以使用多次。。

题目是枚举所有可能性的结果,所以可以使用回溯,尝试着看看是否满足要求。

 

class Solution {
public List<List<Integer>> combinationSum(int[] nums, int target) {
   /**
   这个题是穷举所有情况,回溯的可能性比较大
   */
        Arrays.sort(nums);
    List<List<Integer>> result=new ArrayList<List<Integer>>();
    backtracking(result,new ArrayList<Integer>(),nums,target,0,0);
    return result;
    }
    
    public void backtracking(List<List<Integer>> result,List<Integer> tmp,int[] nums,int target,int sum,int index){
        if(sum>target) return ;
        if(sum==target) {
            result.add(new ArrayList<Integer>(tmp));
            return ;
        }
        
        if(index>nums.length-1) return ;
        
        for(int i=index;i<nums.length;i++){
            tmp.add(nums[i]);
            backtracking(result,tmp,nums,target,sum+nums[i],i);
            tmp.remove(tmp.size()-1);
        }
    }
}

 

 

posted on 2017-12-26 11:01  夜的第八章  阅读(162)  评论(0编辑  收藏  举报

导航