[LintCode]Combination Sum

http://www.lintcode.com/en/problem/combination-sum/#

求所有combination,和为target,combination为非降序。每个数字可以被取多次







public class Solution {
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    // 如果candidates有重复数字,首先要去重
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // write your code here
        List<List<Integer>> res = new ArrayList();
        Arrays.sort(candidates);
        int len = 1;
        for (int i = 1; i < candidates.length; i++) {
            if (candidates[i] != candidates[i - 1]) {
                candidates[len++] = candidates[i];
            }
        }
        combination(candidates, target, res, new ArrayList(), 0, len);
        return res;
    }
    private void combination(int[] candidates, int target, List<List<Integer>> res, List
        <Integer> list, int pos, int len) {
        if (target == 0) {
            res.add(new ArrayList(list));
            return;
        } else if (target < 0) {
            return;
        }
        for (int i = pos; i < len; i++) {
            list.add(candidates[i]);
            combination(candidates, target - candidates[i], res, list, i, len);
            list.remove(list.size() - 1);
        }
    }
}



如果每个数字只能被取一次

http://www.lintcode.com/en/problem/combination-sum-ii/






public class Solution {
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        // write your code here
        List<List<Integer>> res = new ArrayList();
        Arrays.sort(nums);
        combination(nums, target, res, new ArrayList(), -1);
        return res;
    }
    private void combination(int[] nums, int target, List<List<Integer>> res, List<Integer> 
        list, int pos) {
        if (target == 0) {
            res.add(new ArrayList(list));
            return;
        }
        if (target < 0) {
            return;
        }
        for (int i = pos + 1; i < nums.length; i++) {
            if (i != pos + 1 && nums[i] == nums[i - 1]) {
                continue;
            }
            list.add(nums[i]);
            combination(nums, target - nums[i], res, list, i);
            list.remove(list.size() - 1);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值