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 }
  • 相关阅读:
    SVN服务器搭建和使用(一)
    TortoiseSVN客户端重新设置用户名和密码
    UML类图
    String_Helper
    windows常用命令集锦
    JavaScript性能优化小知识总结(转)
    Uploadify 3.2 参数属性、事件、方法函数详解
    记一次 Hibernate 插入数据中文乱码报错解决
    Spring——ClassPathXmlApplicationContext(配置文件路径解析 1)
    Mybatis错误——Could not find parameter map java.util.Map
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388697.html
Copyright © 2011-2022 走看看