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

    Given a set of candidate numbers (C) 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.
    • 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 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

    题目大意:给一个候选数组,一个目标值,从候选数组找出所有和等于目标值的List,候选数组元素可以重复。

    解题思路:还是用回溯的方式来做,因为可以重复,所以每次都可以从当前元素开始往后依次添加到List,递归判断,然后回溯。

        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if (candidates == null || candidates.length == 0) {
                return res;
            }
            List<Integer> tmp = new ArrayList<>();
            helper(res, tmp, 0,candidates, target);
            return res;
        }
    
        private void helper(List<List<Integer>> res, List<Integer> tmp, int start,int[] candidates, int target) {
            if (0 == target) {
                res.add(new ArrayList<>(tmp));
    //            System.out.println(tmp);
                return;
            }
            for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
                tmp.add(candidates[i]);
                helper(res, tmp, i,candidates, target - candidates[i]);
                tmp.remove(tmp.size() - 1);
                int ca = candidates[i];
                while(i<candidates.length&&ca==candidates[i]){
                    i++;
                }
            }
        }
  • 相关阅读:
    养花
    【bzoj1419】Red is good
    C++模板
    逆元求组合数
    【IOI2000】【洛谷1435】回文字串
    Centos 下启动mysql 报错: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (111)解决方法
    linux系统下进行安装phpMyAdmin(基于Centos)
    达梦数据的安装(Windows10 、linux环境下、麒麟系统下)
    2020-3-3 链表刷题(203. 移除链表元素)
    2020-02-03 刷题
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4538445.html
Copyright © 2011-2022 走看看