Combination Sum I

题:

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] 

题意:

    给一个数组C和一个目标值T, 找出所有的满足条件的组合:使得组合里面的数字之和等于T,并且一些数字可以从C中午先选择。

分析:

      深度优先搜索(DFS)是搜索算法的一种。最早接触DFS应该是在二叉树的遍历里面,二叉树的先序、中序和后序遍历实际上都属于深度优先遍历,实质就是深度优先搜索,后来在图的深度优先遍历中则看到了更纯正的深度优先搜索算法。

     通常,我们将回溯法和DFS等同看待,可以用一个等式表示它们的关系:回溯法=DFS+剪枝。所以回溯法是DFS的延伸,其目的在于通过剪枝使得在深度优先搜索过程中如果满足了回溯条件不必找到叶子节点,就截断这一条路径,从而加速DFS。实际上,即使没有剪枝,DFS在从下层回退到上层的时候也是一个回溯的过程,通常这个时候某些变量的状态。DFS通常用递归的形式实现比较直观,也可以用非递归,但通常需要借组辅助的数据结构(比如栈)来存储搜索路径。


 

   public class Solution {
    List<List<Integer>> result;
List<Integer> solu;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
        result = new ArrayList<>();
        solu = new ArrayList<>();
        Arrays.sort(candidates);
        getCombination(candidates, target, 0, 0);
        return result;
    }
public void getCombination(int[] candidates, int target, int sum, int level){
if(sum>target) return;
if(sum==target){
result.add(new ArrayList<>(solu));
return;
}
for(int i=level;i<candidates.length;i++){
sum+=candidates[i];
solu.add(candidates[i]);
getCombination(candidates, target, sum, i);
solu.remove(solu.size()-1);
sum-=candidates[i];
}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值