zoukankan      html  css  js  c++  java
  • leetcode -- Combination Sum

    Given a set of candidate numbers (C) 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.
    • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
    • 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] 

    本题是求解所有可能的组合数,可用DFS来求解,如需求解最优解,需使用DP

    DFS的递归函数中只处理当前状态节点n,而不关心它的下一状态

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int len = candidates.length;
     6         ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
     7         if(len == 0)
     8             return results;
     9         
    10         Arrays.sort(candidates);
    11         
    12         ArrayList<Integer> result = new ArrayList<Integer>();
    13         int level = 0;
    14         int sum = 0;
    15         DFS(candidates, level, sum, target, result, results);
    16         return results;
    17     }
    18     
    19     public void DFS(int[] candidates, int level, int sum, int target, ArrayList<Integer> result,
    20         ArrayList<ArrayList<Integer>> results){
    21         if(sum > target)
    22             return;
    23         
    24         if(sum == target){
    25             ArrayList<Integer> tmp = new ArrayList<Integer>();
    26             tmp.addAll(result);
    27             results.add(tmp);
    28             return;
    29         }
    30         if(sum < target){
    31             for(int i = level; i < candidates.length; i++){
    32                 sum += candidates[i];
    33                 result.add(candidates[i]);
    34                 DFS(candidates, i, sum, target, result, results);
    35                 result.remove(result.size() - 1);
    36                 sum -= candidates[i];
    37             }
    38         }
    39     }
    40 }

    ref:

    DFS 算法入门:http://rapheal.iteye.com/blog/1526863

  • 相关阅读:
    php中php5_module、fastcgi和php-fpm是什么东西??
    Java中接口(interface)和抽象类(abstract)的区别
    Http中的status code
    排查服务器遇到的错误-查看tomcat日志命令
    Java中对list集合进行判空
    Java中的序列化、反序列化-serializable和serialversionUID
    wave文件头之笔记
    乱七八糟的流
    CentOS新建虚拟机后配置静态IP
    rabbitMQ
  • 原文地址:https://www.cnblogs.com/feiling/p/3234904.html
Copyright © 2011-2022 走看看