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);
            }
        }
  • 相关阅读:
    数据库设计三大范式
    导航下拉栏 简单方法
    原生js制作弹出框
    原生js和jquery实现图片轮播特效
    用js 做大图轮播方法(一)
    Apple 企业开发者账号申请记录
    libnids介
    n++ ++n
    空指针为什么能调用成员函数?
    c++单例
  • 原文地址:https://www.cnblogs.com/xiehuazhen/p/10146108.html
Copyright © 2011-2022 走看看