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.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
A solution set is:
1 |
|
Analysis
这道题看起来还是挺麻烦的,要搜索所有的解,对于解题来看,先简单的想一个例子,然后walk through,仔细理理应该可以想出来需要一步步的搜索加上回溯。相对来说还是比较复杂了
Solution
1 |
|
1 |
|
1 |
|
Call stack
简单的来画一个call stack,帮助理解。假设需要搜索的数组为[2,3,7]
, target 为 7
。外层需要有一个循环来不断的找下一个元素,如果满中条件,则找到一个结果,如果不满足条件,则对元素遍历收索一遍,然后再退回来,重新开始一次新的遍历搜索
Python 知识点
先看例子
1 |
|
Expression a += [5]
modifies the list in-place, means it extends the list such that “list1” and “list2” still have the reference to the same list.
Expression a = a + [6]
creates a new list and changes “list1” reference to that new list and “list2” still refer to the old list. so here a = a + [6]
makes a completely a different reference from b
while previously, a
and b
have the reference to the same list.