zoukankan      html  css  js  c++  java
  • leecode---39---数组,dfs,回溯法---求所有的组合为target,数字无重复

    给了个数组和目标值,要找到几个数字和为目标值。
    dfs的时候入参有:总结果,当前数字记录,当前数字总和,数组,数组下标,目标值。
    如果当前总和超过target,退出dfs
    如果当前总和==target,记录结果
     
     

     
     
    题意
    给一个数组和target,求全部组合,其中数字可以重复使用,数组中没有重复数字
     
    分析
     
     
     
    代码
    class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            List<Integer> temp = new ArrayList<Integer>();
            if(candidates == null || candidates.length <= 0 || target < 0) return result;
            dfs(result,temp,candidates,0,0,target);
            return result;
        }
        
        public void dfs(List<List<Integer>> result,List<Integer> temp,int[] nums,int pos,int curSum,int target){
            //1.直接退出循环情况
            if (curSum > target) return;
            
            //2.结果情况
            if (curSum == target) {
                result.add(new ArrayList<Integer>(temp));
            }
            
            //3.普通情况---选择条件:因为数字可以重复使用且无重复,所以从pos到末尾都可以用
            //4.是否回溯---因为记录了路程,所以进行下一种选择的时候需要把上一种选择剔除掉。
            for (int i=pos; i < nums.length; i++) {
                temp.add(nums[i]);
                curSum+=nums[i];
                dfs(result,temp,nums,i,curSum,target);
                temp.remove(temp.size() - 1);
                curSum -= nums[i];
            }
        }
    }
  • 相关阅读:
    set, bag, list, map的语义
    ExtJs 自定义Vtype验证
    详解.NET中的动态编译技术
    IL汇编语言介绍(译)
    C# 文件操作相关
    邮件系统
    关于Nhibernate中的多数据库支持
    .NET中 用C#操纵IIS
    ExtJS日期格式
    完全详解使用Resource实现多语言的支持
  • 原文地址:https://www.cnblogs.com/buptyuhanwen/p/8985585.html
Copyright © 2011-2022 走看看