Lintcode153 Combination Sum II solution 题解

【题目描述】

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

Each number inCmay only be used once in the combination.

Notice

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.

给出一组候选数字(C)和目标数字(T),找出C中所有的组合,使组合中数字的和为T。C中每个数字在每个组合中只能使用一次。

【注】

所有的数字(包括目标数字)均为正整数。

元素组合(a1,a2, … ,ak)必须是非降序(ie,a1≤a2≤ … ≤ak)。

解集不能包含重复的组合。

【题目链接】

www.lintcode.com/en/problem/combination-sum-ii/

【题目解析】

先对所有数字排序,之后按照深度优先搜索将index + 1 ~ len之间所有的数字都尝试放在结果集中,比较sum与target的大小,如果和 target一样大,就把当前组合结果放入集合中(为了避免重复),如果比target大,因为所有数都是正数,所以要提前return(不这样做会超时)。最后把集合中的所有结果放入一个二维数组result中,返回result即可。

【参考答案】

www.jiuzhang.com/solutions/combination-sum-ii/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【题目描述】 Given a set of candidate numbers (C) and a target ...
    程风破浪会有时阅读 3,405评论 0 0
  • 标签: C++ 算法 LeetCode DFS 每日算法——leetcode系列 问题 Combinatio...
    CarlBlack阅读 3,146评论 0 0
  • 标签: C++ 算法 LeetCode 数组 DFS 每日算法——leetcode系列 问题 Combinat...
    CarlBlack阅读 2,472评论 0 0
  • 前天给你看了那篇文章后,昨天比较忙,就只写下了一些灵感,所以今天把文章补上。 当时你表现的很生气,你觉得我很多话都...
    水木泽林阅读 1,657评论 0 0
  • 前段时间股市很火,网上很应景的流行一句话说“侠之大者,为国接盘”,细想起来,会发现大字在我们日常词汇中的出现...
    须弥沙阅读 6,442评论 0 3

友情链接更多精彩内容