• Combination Sum II


    Combination Sum II

    问题:

    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.

    思路:

      常见的回溯问题

    我的代码:

    public class Solution {
        public List<List<Integer>> combinationSum2(int[] num, int target) {
            if(num == null || num.length == 0)    return rst;
            List<Integer> list = new ArrayList<Integer>();
            Arrays.sort(num);
            helper(list, num, target, 0, 0);
            return rst;
        }
        private List<List<Integer>> rst = new ArrayList<List<Integer>>();
        public void helper(List<Integer> list, int[] candidates, int target, int sum, int start)
        {
            if(sum > target)    return;
            if(sum == target)
            {
                if(!rst.contains(list))
                    rst.add(new ArrayList(list));
                return;
            }
            for(int i = start ; i < candidates.length; i++)
            {
                list.add(candidates[i]);
                helper(list, candidates, target, sum + candidates[i], i + 1);
                list.remove(list.size() - 1);
            }
        }
    }
    View Code

     学习之处:

      集合中的元素都访问到了,所以时间复杂度为O(2n),其实本质上就是一个二叉树

  • 相关阅读:
    VINTF
    Excel 公式
    SSIS ODBC方式连接mysql数据库
    SSIS错误汇总
    linux防火墙(转)
    如何查询域名的MX、A、DNS、txt、cname记录
    IP反向解析
    Visual Studio 内存泄漏检测方法
    strcpy慎用
    main函数前后执行代码
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4326331.html
Copyright © 2020-2023  润新知