zoukankan      html  css  js  c++  java
  • LeetCode--Combination Sum --ZZ

    http://blog.csdn.net/linhuanmars/article/details/20828631

    这个题是一个NP问题,方法仍然是N-Queens中介绍的套路。基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的。Java代码如下: 

     1 public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
     2     ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
     3     if(candidates == null || candidates.length==0)
     4         return res;
     5     Arrays.sort(candidates);
     6     helper(candidates,0,target,new ArrayList<Integer>(),res);
     7     return res;
     8 }
     9 private void helper(int[] candidates, int start, int target, ArrayList<Integer> item, 
    10 ArrayList<ArrayList<Integer>> res)
    11 {
    12     if(target<0)
    13         return;
    14     if(target==0)
    15     {
    16         res.add(new ArrayList<Integer>(item));
    17         return;
    18     }
    19     for(int i=start;i<candidates.length;i++)
    20     {
    21         if(i>0 && candidates[i]==candidates[i-1])
    22             continue;
    23         item.add(candidates[i]);
    24         helper(candidates,i,target-candidates[i],item,res);
    25         item.remove(item.size()-1);
    26     }
    27 }

    注意在实现中for循环中第一步有一个判断,那个是为了去除重复元素产生重复结果的影响,因为在这里每个数可以重复使用,所以重复的元素也就没有作用了,所以应该跳过那层递归。这道题有一个非常类似的题目Combination Sum II,有兴趣的朋友可以看看,一次搞定两个题哈。

  • 相关阅读:
    sdut1282Find the Path (floyd变形)
    sdut1933WHUgirls(dp)
    二分图入门题集
    Codeforces Round #230 (Div. 1)
    PHP中关于 basename、dirname、pathinfo 详解
    nginx php mysql日志配置
    确保 PHP 应用程序的安全 -- 不能违反的四条安全规则
    mysql日期时间处理
    mysql索引类型和索引方法
    php Redis函数使用总结(string,hash,list, set , sort set )
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4032335.html
Copyright © 2011-2022 走看看