zoukankan      html  css  js  c++  java
  • Combination Sum II —— LeetCode

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    Each number in C may only be used once in the combination.

    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 10,1,2,7,6,1,5 and target 8
    A solution set is: 
    [1, 7] 
    [1, 2, 5] 
    [2, 6] 
    [1, 1, 6]

    题目大意:跟上一题类似,但是有点区别就是候选集中的元素只能出现一次。

    解题思路:每次从当前元素的下一个开始计算sum,并把candidate加入List,并且跳过重复元素。

        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if (candidates == null || candidates.length == 0) {
                return res;
            }
            Deque<Integer> tmp = new ArrayDeque<>();
            Arrays.sort(candidates);
            helper(res, tmp, 0, target, candidates);
            return res;
        }
    
        private void helper(List<List<Integer>> res, Deque<Integer> tmp, int start, int target, int[] candidate) {
            if (target == 0) {
                res.add(new ArrayList<>(tmp));
    //            System.out.println(tmp);
                return;
            }
            for (int i = start; i < candidate.length && target >= candidate[i]; i++) {
                tmp.addLast(candidate[i]);
                helper(res, tmp, i + 1, target - candidate[i], candidate);
                tmp.removeLast();
                while (i < candidate.length - 1 && candidate[i + 1] == candidate[i]) {
                    i++;
                }
            }
        }
  • 相关阅读:
    sublime 标题乱码,内容正常
    解决PHP7+ngnix+yaf框架404的问题
    调用RPC接口出现错误:Yar_Client_Transport_Exception (16) curl exec failed 'Timeout was reached'
    xhprof安装和使用
    单点登录
    如何让局域网内Apache互相访问
    lnmp
    virtualbox
    微信省市区 Mysql数据库
    lnmp
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4538784.html
Copyright © 2011-2022 走看看