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. 利用autoit自动关闭指定标题窗口

     最近使用PL/SQL Developer 比较两个数据库数据差异,因部分表上没有主键,PL/SQL 就会弹出一个确认框提示某某表没有主键.因为有很多表没有主键,就不停的弹出确认窗口,得不停的点击 ...

  2. Gym 100570E : Palindrome Query

    De Prezer loves palindrome strings. A string s1s2...sn is palindrome if and only if it is equal to i ...

  3. Palindrome Linked List 解答

    Question Given a singly linked list, determine if it is a palindrome. Follow up:Could you do it in O ...

  4. hdu2059 龟兔赛跑

    hdu2059 龟兔赛跑 动态规划 题目描述: Problem Description 据说在很久很久以前,可怜的兔子经历了人生中最大的打击——赛跑输给乌龟后,心中郁闷,发誓要报仇雪恨,于是躲进了杭州 ...

  5. obiz

    ofbiz 安装 1. 由 binary 安装: 由 binary 安装非常简单, 以下是安装方法: 下载ofbiz-2.0-beta1-complete.tar.gz, 注意不是ofbiz-2.0- ...

  6. nyoj 234 吃土豆

    描述 Bean-eating * grid. Now you want to eat the beans and collect the qualities, but everyone must ob ...

  7. 用WIFI为什么连不上VPN

    因为是做服务器的,经常需要通过VPN连接到公司的服务器处理一些事件. 但最近一次在寝室通过WIFI连接VPN时却报“错误 619:不能建立到远程计算机的连接,因用于此端口的连接已关闭”.我的第一反应是 ...

  8. Unity 白猫操作小实例

    最近师兄找我说白猫的操作如何做,  0.0 结果白猫没有android的客户端玩不了,看了下视频介绍就简单做了下 效果图:   核心代码: using UnityEngine; using Syste ...

  9. pyQt事件处理

    Qt事件处理01 Qt处理事件的第二种方式:"重新实现QObject::event()函数",通过重新实现event()函数,可以在事件到达特定的事件处理器之前截获并处理他们.这种 ...

  10. cocos2d-x3.2中怎样优化Cocos2d-X游戏的内存

    在游戏项目优化中都会碰到一个问题,怎样既能降低内存又能尽量降低包的大小?在实际项目中有些经验分享一下,其实2D游戏中最占内存的就是图片资源,一张图片使用不同的纹理格式带来的性能差异巨大.下表是我在IO ...