Leetcode 39. 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值

2.每一层都要维护一个属于自己的list,传递给下一层的时候创建新的list进行传递(非常重要,每层维护的list容易混淆)

3.后一层都要从前一层选中的数的标号开始往后查找,并且要跳过前后两个数相同的坐标,这样避免出现重复

ps:貌似可以使用深度搜索做.目测效率不高,没有尝试
java代码如下

class Solution {
     public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        combineSum(candidates, 0, target, lists, null);
        return lists;
    }

    public void combineSum(int[] candidates, int begin,int target,List<List<Integer>> lists,List<Integer> list) {
        for (int i = begin; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1]) {
                continue;
            }
            int now = candidates[i];
            if (now == target) {
                if (list == null) {
                    list = new ArrayList<Integer>();
                }
                List<Integer> integerList = new ArrayList<Integer>(list);
                integerList.add(now);
                lists.add(integerList);
                continue;

            }
            if (now * 2 <=  target) { //两倍的值小于目标值
                if (list == null) {
                    list = new ArrayList<Integer>();
                }
                List<Integer> integerList = new ArrayList<Integer>(list);
                integerList.add(now);
                combineSum(candidates,i,target - now,lists,integerList);
            }
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值