• leecode---40---数组,dfs---求所有的组合为target,有重复数组


    dfs的入参是这样:总结果,当前结果,当前总和,数组,数组下标,target
    如果当前结果>target直接退出
    如果==target,记录结果
    总和小于target说明当前需要加数字进去了,但是可以加的数字从pos位置开始往后都可以加入到数组中。这边因为可能有重复,那么如果当前数字和前面数字重复了就直接continue跳过。
     
     
     

     
     
    题意
    给一个数组和一个目标数,其中数组有重复的,找组合为target的所有结果
     
     
    分析
    回溯法。先将数组进行排序,遍历的时候如果重复了就直接跨过去。
    因为不能够重复使用数字,所以回溯的时候要跨过去。
     
     
    代码
    class Solution {
        
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        int target ;
        
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            if(candidates == null || candidates.length <= 0 || target < 0) return result;
            this.target = target;
            Arrays.sort(candidates);
            backTrack(candidates,0,new LinkedList<Integer>(),0);
            return result;
        }
        
        //回溯法,回溯过程中:
        //1.不满足条件的直接return,这边curSum超出target
        //2.满足的直接记录到全局变量中
        //3.否则继续回溯,回溯记录路径的时候记得加入和弹出
        public void backTrack(int[] nums,int curSum,List<Integer> temp,int start) {
            if (curSum > target) return;
            if (curSum == target) {
                result.add(new LinkedList(temp));
                return;
            }
            for (int i = start; i < nums.length; i++) {
                if (i > start && nums[i] == nums[i - 1])continue;
                temp.add(nums[i]);
                backTrack(nums,curSum + nums[i],temp,i + 1);
                temp.remove(temp.size() - 1);
            }
        }
    }
     
  • 相关阅读:
    MyEclipse中配置Hibernate
    struts2_对Map进行双层迭代
    Hibernate关联关系全集
    CodeIgniter+Smarty配置
    去掉php框架CI默认url中的index.php【整理】
    jquery的show方法是display:block还是display:inline呢?
    Codeigniter中的Error【转】
    去除 inlineblock 空隙终极解决方案
    jquery三级折叠菜单
    css实现页面文字不换行、自动换行、强制换行
  • 原文地址:https://www.cnblogs.com/buptyuhanwen/p/8985625.html
Copyright © 2020-2023  润新知