zoukankan      html  css  js  c++  java
  • 39. Combination Sum

    Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [2, 3, 6, 7] and target 7
    A solution set is: 

    [
      [7],
      [2, 2, 3]
    ]

    本题和Permutations1,2比较类似,不过这里面的回溯法的剪枝函数是target,回溯法的特点是可以解决一个问题的所有解或者任意解,且采用深度优先遍历,用于解决组合数比较大的问题,回溯法
    具有约束函数和限界函数两个函数。
    下面说一下这个题和之前的permutations1,2区别,之前的1是不存在重复元素的时候,且不会遍历同样的元素。2的问题是有重复的的元素,创建一个数组来记录是否used。本题是函数里面传递一个
    cur索引,这样不会回头重新计算。代码如下:
     1 public class Solution {
     2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         Arrays.sort(candidates);
     5         backtracking(res,candidates,target,new ArrayList<Integer>(),0);
     6         return res;
     7     }
     8     public void backtracking(List<List<Integer>> res,int[] candidates,int target,List<Integer> list,int start){
     9         if(target==0){
    10             res.add(new ArrayList<Integer>(list));
    11         }else{
    12             for(int i=start;i<candidates.length;i++){
    13                 int sum = target-candidates[i];
    14                 if(sum<0) break;
    15                 list.add(candidates[i]);
    16                 backtracking(res,candidates,sum,list,i);
    17                 list.remove(list.size()-1);
    18             }
    19         }
    20     }
    21 }
  • 相关阅读:
    windows RabbitMQ Server 环境配置中的一些坑
    Redis自定义fastJson Serializer
    如何使用Feign构造多参数的请求
    跨域访问支持(Spring Boot、Nginx、浏览器)
    chrome浏览器的跨域设置
    Jenkins手把手图文教程[基于Jenkins 2.164.1]
    Spring Boot 2发送邮件手把手图文教程
    poi读取Excel模板并修改模板内容与动态的增加行
    Lock类-ReentrantLock的使用
    类ThreadLocal的使用与源码分析
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388697.html
Copyright © 2011-2022 走看看