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. 【多线程】--生产者消费者模式--synchronized版本

    在实现生产者消费者模式之前,我们先了解一下线程的5种状态:被创建.运行.冻结.消亡.阻塞,如下图: 在Jdk1.5发布之前,我们实现生产者消费者模式一般使用synchronized + while循环 ...

  2. [转]CodeIgniter与Zend Acl结合实现轻量级权限控制

    Tag :CodeIgniter  Zend Acl 权限控制 1. Zend_Acl简介 Zend_Acl 为权限管理提供轻量并灵活的访问控制列表 (ACL,access control list) ...

  3. Filter简单介绍

    一.简单介绍 Filter也称为过滤器,WEB开发者通过Filter技术.对webserver管理的全部web资源:比如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截.从而实 ...

  4. BOOST 线程完全攻略 - 结束语

    modulethread扩展多线程破解通讯 全文介绍了3个boost::thread的扩展类,希望能给大家书写多线程代码带来便捷. thread -> controlled_module_ex ...

  5. 前端--关于CSS

    CSS全名层叠样式表,层叠的含义有三个:1.按照特殊性的高低,特殊性高的覆盖特殊性低的样式声明:2.不同属性的样式声明要合并:3.后出现的相同的样式声明覆盖先出现的.所以要改变样式的优先级也有三种方法 ...

  6. JSP基础学习(二)

    1.JSP页面的内容组成 静态部分:标准的HTML标签.静态的页面内容,这些内容与静态的HTML页面相同 动态部分:这些由java程序来动态生成 2.<% out.println(new jav ...

  7. Hibernate常见接口说明

    (一)SessionFactory 1. getCurrentSession()和openSession()区别 getCurrentSession创建的session会和绑定到当前线程,而openS ...

  8. pp to write

    vanishing gradient problem multi-dimensional lstm

  9. TextView之一:子类的常用属性

    TextView常见的子类包括EditText,Button,CheckBox, RadioButton等. 1.EditText EditText继承自TextView,因此TextView所有属性 ...

  10. Python多线程同步命令行模拟进度显示

    最近在一个Python(3.5)的小项目中需要用到多线程加快处理速度,同时需要显示进度,于是查了些资料找到几个实现方法:线程池的map-reduce和Queue结合线程的实现.这里简单的实例介绍一下Q ...