【题目描述】
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即可。
【参考答案】