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]
题意分析:
本题是给定一个数字集合(可能有重复)和一个目标值,让你找出所有可能的组合,使之和为目标值。所有的数字可以使用无限次,要求得到的组合不能有重复,并且组合里面的数字必须是升序。
解答:
思路是循环拿每个数字去迭代,找出所有的组合,满足条件返回,不满足退回上一步继续下一个数字的尝试。看特征,仍然是用回溯法的思路去做。
AC代码:
class Solution(object): def combinationSum(self, candidates, target): ret_list = [] def backtracing(target, candidates, index, temp_list): if target == 0: ret_list.append(temp_list) elif target > 0: for i in xrange(index, len(candidates)): backtracing(target - candidates[i], candidates, i, temp_list + [candidates[i]]) backtracing(target, sorted(list(set(candidates))), 0, []) return ret_list