zoukankan      html  css  js  c++  java
  • 给定一组数和一个目标值,返回和为目标值的集合(集合中的元素可重复)

    以下为原题:

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where
    the candidate numbers sums to target.The same repeated number may be chosen from candidates unlimited number of times.Note:All numbers (including
    target) will be positive integers.The solution set must not contain duplicate combinations. Example 1: Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7], [2,2,3] ] Example 2: Input: candidates = [2,3,5], target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ]

    思路:

    1.以target<=0为基准:若target<0,return;若target=0,add,return。

    2.每一层递归都遍历给定的数组,遍历的起始位置是上一层递归正在遍历的位置。如果target>0,则在下一层递归中target减去当前递归层正被遍历的元素。

    代码如下:

        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            if(candidates==null||candidates.length==0)
                return new ArrayList<>();
            List<List<Integer>> allRes = new ArrayList<>();
            combinationSumDetail(candidates,target,new ArrayList<>(),allRes,0);
            return allRes;
        }
    
        private void combinationSumDetail(int[] candidates, int target, List<Integer> subRes, List<List<Integer>> allRes, int start){
            if(target<0)
                return;
            if(target==0){
                allRes.add(new ArrayList<>(subRes));
                return;
            }
            for(int i=start;i<candidates.length;++i){
                subRes.add(candidates[i]);
                combinationSumDetail(candidates,target-candidates[i],subRes,allRes,i);
                subRes.remove(subRes.size()-1);
            }
        }
  • 相关阅读:
    Java虚拟机(JVM)中的内存设置详解
    设置TOMCAT的JVM虚拟机内存大小
    什么是SQL注入式攻击
    常见的数据库基础面试题大全
    Struts1与Struts2的12点区别
    sql server导出insert语句
    jsp 将html字符串输出html标签
    GC 基础
    jstl fn标签
    Struts2 中result type属性说明
  • 原文地址:https://www.cnblogs.com/xiehuazhen/p/10146108.html
Copyright © 2011-2022 走看看