码迷,mamicode.com
首页 > 其他好文 > 详细

29.Combination Sum(和为sum的组合)

时间:2019-04-30 19:53:06      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:from   .com   null   com   example   mes   out   就是   sum   

Level:

??Medium

题目描述:

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

思路分析:

? 先对数组进行排序,方便后面递归回溯的过程中进行剪枝。然后设置一个变量sum,记录当前序列的数字和,如果sum的值等于target那么当前序列就是结果的一种,我们利用回溯的思想,找出所有满足要求得解。

代码:

public class Solution{
    List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>>combinationSum(int []candidates,int target){
        if(candidates==null||candidates.length==0)
            return res;
        Arrays.sort(candidates);//排序,方便后面剪枝
        find(candidates,0,0,target,new ArrayList<>());
        return res;
    }
    public void find(int[]candidates,int start,int sum,int target,ArrayList<Integer>list){
        if(sum==target){
            res.add(new ArrayList<Integer>(list));
            return;
        }
        for(int i=start;i<candidates.length;i++){
            if(sum+candidates[i]<=target){
                list.add(candidates[i]);
               find(candidates,i,sum+candidates[i],target,list);
                list.remove(Integer.valueOf(candidates[i]));
            }else{
                break; //剪枝
            }
        }
    }
}

29.Combination Sum(和为sum的组合)

标签:from   .com   null   com   example   mes   out   就是   sum   

原文地址:https://www.cnblogs.com/yjxyy/p/10797665.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!