• 给定一组数和一个目标值,返回和为目标值的集合(集合中的元素可重复)


    以下为原题:

    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);
            }
        }
  • 相关阅读:
    1029: [JSOI2007]建筑抢修
    1028: [JSOI2007]麻将
    1050 棋盘染色 2
    1026: [SCOI2009]windy数
    1074: [SCOI2007]折纸origami
    839. Optimal Marks
    1024: [SCOI2009]生日快乐
    1025: [SCOI2009]游戏
    1023: [SHOI2008]cactus仙人掌图
    对前面的总结
  • 原文地址:https://www.cnblogs.com/xiehuazhen/p/10146108.html
Copyright © 2020-2023  润新知