Combination Sum II

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

Each number in C may only be used once in the combination.

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 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6]

解法一:

最直接的想法就是把所有子集都列出来,然后逐个计算和是否为target

但是考虑到空间复杂度,10个数的num数组就有210个子集,因此必须进行“剪枝”,去掉不可能的子集。

先对num进行排序。

在遍历子集的过程中:

(1)单个元素大于target,则后续元素无需扫描了,直接返回结果。

(2)单个子集元素和大于target,则不用加入当前的子集容器了。

(3)单个子集元素和等于target,加入结果数组。

class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > result;
vector<vector<int> > subsets;
vector<int> empty;
subsets.push_back(empty); sort(num.begin(), num.end());
for(int i = ; i < num.size();)
{//for each number
int count = ;
int cur = num[i];
if(cur > target) //end
return result;
while(i < num.size() && num[i] == cur)
{//repeat count
i ++;
count ++;
}
int size = subsets.size(); //orinigal size instead of calling size() function
for(int j = ; j < size; j ++)
{
vector<int> sub = subsets[j];
int tempCount = count;
while(tempCount --)
{
sub.push_back(cur);
int sum = accumulate(sub.begin(), sub.end(), );
if(sum == target)
{
result.push_back(sub);
subsets.push_back(sub);
}
else if(sum < target)
subsets.push_back(sub);
}
}
}
return result;
}
};

解法二:递归回溯

需要注意的是:

1、在同一层递归树中,如果某元素已经处理并进入下一层递归,那么与该元素相同的值就应该跳过。否则将出现重复。

例如:1,1,2,3

如果第一个1已经处理并进入下一层递归1,2,3

那么第二个1就应该跳过,因为后续所有情况都已经被覆盖掉。

2、相同元素第一个进入下一层递归,而不是任意一个

例如:1,1,2,3

如果第一个1已经处理并进入下一层递归1,2,3,那么两个1是可以同时成为可行解的

而如果选择的是第二个1并进入下一层递归2,3,那么不会出现两个1的解了。

class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
sort(num.begin(), num.end());
vector<vector<int> > ret;
vector<int> cur;
Helper(ret, cur, num, target, );
return ret;
}
void Helper(vector<vector<int> > &ret, vector<int> cur, vector<int> &num, int target, int position)
{
if(target == )
ret.push_back(cur);
else
{
for(int i = position; i < num.size() && num[i] <= target; i ++)
{
if(i != position && num[i] == num[i-])
continue;
cur.push_back(num[i]);
Helper(ret, cur, num, target-num[i], i+);
cur.pop_back();
}
}
}
};

【LeetCode】40. Combination Sum II (2 solutions)的更多相关文章

  1. 【LeetCode】40. Combination Sum II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:回溯法 日期 题目地址:ht ...

  2. 【一天一道LeetCode】#40. Combination Sum II

    一天一道LeetCode系列 (一)题目 Given a collection of candidate numbers (C) and a target number (T), find all u ...

  3. 【LeetCode】040. Combination Sum II

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  4. 【LeetCode】113. Path Sum II 解题报告(Python)

    [LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

  5. [Leetcode][Python]40: Combination Sum II

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 40: Combination Sum IIhttps://oj.leetco ...

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

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

  7. 【LeetCode】216. Combination Sum III

    Combination Sum III Find all possible combinations of k numbers that add up to a number n, given tha ...

  8. LeetCode OJ 40. Combination Sum II

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

  9. 【LeetCode】167. Two Sum II - Input array is sorted

    Difficulty:easy  More:[目录]LeetCode Java实现 Description Given an array of integers that is already sor ...

随机推荐

  1. Linux 挂载和卸载U盘

    一般的U盘挂载方法: mount [-fnrsvw]  [-t vfstype] [-o options] device dir 参数:device表示要挂载的设备,dir表示挂载点 -t 指定设备的 ...

  2. uva 10160 Servicing Stations(DFS+剪枝)

    Servicing stations A company offers personal computers for sale in N towns (3 <= N <= 35). The ...

  3. 网站日志访问记录组件UserVisitLogsHelp开源了!

    之前在<一种基于自定义代码记录用户访问日志在Sharepoint网站的应用方法!>一文利用本人几年前的开发的UserVisitLogsHelp组件进行了网站用户访问日志记录,可用于网站分析 ...

  4. 使用SqlServer中的float类型时发现的问题

    在做项目中,使用了float类型来定义一些列,如:Price,但是发现了很多问题1.当值的位数大于6位是float型再转varchar型的时候会变为科学技术法显示    此时只好将float型转换成n ...

  5. 转: 用 Eclipse 平台进行 C/C++ 开发

    http://www.ibm.com/developerworks/cn/linux/opensource/os-ecc/index.html

  6. Java Web -- Servlet(5) 开发Servlet的三种方法、配置Servlet具体解释、Servlet的生命周期(2)

    三.Servlet的生命周期 一个Java servlet具有一个生命周期,这个生命周期定义了一个Servlet怎样被加载并被初始化,怎样接收请求并作出对请求的响应,怎样被从服务中清除.Servlet ...

  7. [Node.js] Load balancing a Http server

    Let's see how to do load balancing in Node.js. Before we start with the solution, you can do a test ...

  8. Postfix接收邮件后转向运行特定的脚本

    本文主要參考:http://serverfault.com/questions/258469/how-to-configure-postfix-to-pipe-all-incoming-email-t ...

  9. POJ 3368 Frequent values (基础RMQ)

    Frequent values Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 14742   Accepted: 5354 ...

  10. Matlab实现:图像边缘提取

    1. 边缘提取算法 方法一:一阶微分算子 Sobel算子 Sobel算子检测方法对灰度渐变和噪声较多的图像处理效果较好,Sobel算子对边缘定位不是很准确,图像的边缘不止一个像素. Roberts算子 ...