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);
            }
        }
  • 相关阅读:
    001.云桌面整体解决方案实施
    Netty基础招式——ChannelHandler的最佳实践
    架构设计之数据分片
    Go是一门什么样的语言?
    Jenkins汉化配置
    Window安装构建神器Jenkins
    uni-app&H5&Android混合开发三 || uni-app调用Android原生方法的三种方式
    如何使用Hugging Face中的datasets
    关于torch.nn.LSTM()的输入和输出
    pytorch中的nn.CrossEntropyLoss()计算原理
  • 原文地址:https://www.cnblogs.com/xiehuazhen/p/10146108.html
Copyright © 2011-2022 走看看