Question

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 (a1, a2, … , 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]

Solution 1 -- BFS

We can also draw the solution tree. For example, input is [2,3,6,7] and 22

                 []

         /     /    \    \

        [2]    [3]    [6]    [7]

      / /  \  \   / \ \    \ \    \

     [2] [3] [6][7]  [3][6][7]  [6][7]  [7]

    .............................................................

We can find silimar regulation as Problem Subsets

Difference is here when we find that current sum of list is greater than target number, we will not add it to next array.

 public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<List<Integer>> current = new ArrayList<List<Integer>>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = candidates.length;
for (int i = 0; i < length; i++) {
List<Integer> list = new ArrayList<Integer>();
list.add(candidates[i]);
if (target == candidates[i])
result.add(list);
if (target > candidates[i])
current.add(list);
map.put(candidates[i], i);
} while (current.size() > 0) {
List<List<Integer>> next = new ArrayList<List<Integer>>();
int l = current.size();
for (int i = 0; i < l; i++) {
List<Integer> tmp = current.get(i);
int ll = tmp.size();
int last = tmp.get(ll - 1);
int index = map.get(last);
// Sum up current list
int total = 0;
for (int j = 0; j < ll; j++)
total += tmp.get(j);
for (int j = index; j < length; j++) {
if (total + candidates[j] < target) {
List<Integer> newList = new ArrayList<Integer>(tmp);
newList.add(candidates[j]);
next.add(newList);
} else if (total + candidates[j] == target) {
List<Integer> newList = new ArrayList<Integer>(tmp);
newList.add(candidates[j]);
result.add(newList);
}
}
}
current = next;
}
return result;
}
}

Solution 2 -- DFS

This also can be solved by DFS. End criterion is leftTarget <= 0.

Refer to this blog, we have two ways to check duplicated solutions.

1.       if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
                 continue;

2.       if(!res.contains(item)) 
                res.add(new ArrayList<Integer>(item));

 public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < candidates.length; i++) {
dfs(candidates, target, i, result, new ArrayList<Integer>());
}
return result;
} private void dfs(int[] nums, int target, int start, List<List<Integer>> result, List<Integer> list) {
if (target < 0)
return;
if (target == 0) {
// Avoid duplicated solutions
if (!result.contains(list))
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = start; i < nums.length; i++) {
list.add(nums[i]);
dfs(nums, target - nums[i], i, result, list);
list.remove(list.size() - 1);
}
}
}

Combination Sum 解答的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. Combination Sum II 解答

    Question Given a collection of candidate numbers (C) and a target number (T), find all unique combin ...

  3. Combination Sum系列问题

    主要使用方法是backtracking. Combination Sum Given a set of candidate numbers (C) and a target number (T), f ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  6. [LeetCode] Combination Sum II 组合之和之二

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  7. [LeetCode] Combination Sum 组合之和

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  8. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  9. LeetCode:Combination Sum I II

    Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...

随机推荐

  1. NLog 2.0.0.2000 使用实例

    原文地址:http://www.cnblogs.com/sorex/archive/2013/01/31/2887174.html ---------------------------------- ...

  2. 利用ant进行编译和发布项目

    本文通过一个示例来解说如何通过ant进行编译和发布项目.本例按如下目录结构来组织项目. D:/web/antsample项目根目录 D:/web/antsample/src源代码目录 D:/web/a ...

  3. PHP设计模式笔记一:准备工作 -- Rango韩老师 http://www.imooc.com/learn/236

    一.编程字体选择 1.选择等宽字体 包括Courier New ,Consolas,Source Code Pro(推荐) 2.环境搭建(建议easyPHP) 二.开发符合PSR规范的基础框架 PSR ...

  4. VirtualBox 扩展包卸载或安装失败(VERR_ALREADY_EXISTS)

    最近在卸载VirtualBox出现了无法卸载的错误.提示为Failed to install the extension. The installer failed with exit code 1: ...

  5. Hash表的扩容(转载)

    Hash表(Hash Table)   hash表实际上由size个的桶组成一个桶数组table[0...size-1] . 当一个对象经过哈希之后.得到一个对应的value , 于是我们把这个对象放 ...

  6. Windows7 无法打开ASA SSL VPN和ASDM首页

    原文地址:Windows7 无法打开ASA SSL VPN 首页和无法打开 ASDM GUI 页面作者:futhy              windows 7 无法打开ASA SSL VPN 和AS ...

  7. CSS 设计彻底研究(三)深入理解盒子模型

    第三章 深入理解盒子模型 盒子模型是CSS控制页面的基础.需要清楚“盒子”的含义是什么,以及盒子的组成.此外,应该理解DOM的基本概念,以及DOM树是如何与一个HTML文档对应的,在此基础上充分理解“ ...

  8. JS截取字符串:slice(),substring()和substr()

    var string='abcdefg' 1.slice() string.slice(startLocation [, endLocation]) ps1:2个参数可以为负数,若参数值为负数,则将该 ...

  9. OpenCV——肤色检测

    一.RGB color space 检测代码如下: void SkinRGB(IplImage* src,IplImage* dst) { //RGB颜色空间 //均匀照明:R>95,G> ...

  10. PHP--变量部分知识点

    PHP全局变量 PHP全局变量作用域不同与C,在函数内部不可以使用全局变量,要在函数内部使用全局变量需要,global $var或者使用超全局变量数组$GLOBALS['var']. 静态变量 PHP ...