leetcode:combination-sum-ii

12 篇文章 0 订阅

题目:https://leetcode.com/problems/combination-sum-ii/
这题主要是使用数组里面的数字求出期望数字的组合可能这个要多一个去重
下面是官方给出的例子

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
 public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);//先排序
        List<List<Integer>> result = new ArrayList<>();
        if (candidates.length == 0 || candidates[0] > target) {//特殊情况处理
            return result;
        }
        List<Integer> tmp = new ArrayList<>();
        getSubSet(result, tmp, 0, target, candidates);//最开始从最小元素开始,差值是target
        return result;
    }

    public static void getSubSet(List<List<Integer>> res, List<Integer> tmp, int index, int remain, int[] nums) {

        for (int i = index; i < nums.length; i++) {
            if (remain - nums[i] < 0) {//也就是遍历到的元素,比target大,所以停止递归
                return;
            } else if (remain - nums[i] == 0) {
                List<Integer> r = new ArrayList<>(tmp);
                r.add(nums[i]);
                res.add(r);//加入到结果集,退出本次递归
                return;
            } else {
                if (i > index && nums[i] == nums[i - 1]) {//要求i大于基准索引,如果该i索引和上一个相等,那就跳过
                    continue;//这个不处理,就是在res.add(r)增加list contains判断,否则输出结果有重复结果集
                }
                tmp.add(nums[i]);//将本元素加入带待定结果集中
                //index=i+1,索引后移,而且差值更新
                getSubSet(res, tmp, i + 1, remain - nums[i], nums);
                tmp.remove(tmp.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] candidates = new int[]{10, 1, 2, 7, 6, 1, 5};
        int target = 8;
        for (List<Integer> a : combinationSum2(candidates, target)) {
            System.out.println(a.toString());
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值