您的位置:首页 > 编程语言 > Python开发

DAY19:leetcode #40 Combination Sum II

2016-09-04 11:35 453 查看
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.
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]
]


Subscribe to see which companies asked this question

对于这道题目,一个简单的思路是先将candidates排序,然后按照DFS检查每条路径是否满足条件。由于题目要求数字不能重复使用(除了在candidates中重复出现的),所以需要对建树操作进行改进。
比如对于candidates = [1,1,2,3],所建立树如下:



建树要点:
1、同一个父节点的孩子节点不能有重复元素(这样是为了防止路径重复)
2、孩子节点>=父节点
3、孩子节点从左到右按照从小到大排列
查找方法:
1、由最左边路径开始,如部分路径和<target,继续向下查找。
2、当进行到某一节点,发现部分路径和>=target,即可结束该路径查找(继续向下只能不断变大),转而向当前节点父节点的右兄弟节点。(如红圈、黄圈所示的跳转)
3、如果不存在父节点的右兄弟,则向继续向上查找(即父节点的父节点的右兄弟)。
比如candidates = [1,1,2,3],target = 3,查找过程如下:



最后附上AC代码:
import copy
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
tree = []
result = set()
candidates_len = len(candidates)
candidates.sort()
for i in range(len(candidates)):
if sum(tree) < target:
tree.append(candidates[i])
if sum(tree) < target:
return []
repeat_count = 1
repeat_num = -1
while(True):
if sum(tree) >= target:
if sum(tree) == target:
result.add(tuple(sorted(copy.deepcopy(tree))))
pos = candidates_len
flag = True
while pos == candidates_len:
del tree[-1]
if len(tree) == 0:
flag = False
break
temp = candidates[candidates_len - candidates[::-1].index(tree[-1]):]
if temp == None or len(temp) == 0:
pos = candidates_len
else:
pos = candidates.index(temp[0])
if not flag:
break
tree[-1] = candidates[pos]
else:
temp_c = candidates[candidates.index(tree[-1])+1:]
if temp_c == []:
pos = candidates_len
flag = True
while pos == candidates_len:
del tree[-1]
if len(tree) == 0:
flag = False
break
temp = candidates[candidates_len - candidates[::-1].index(tree[-1]):]
if temp == None or len(temp) == 0:
pos = candidates_len
else:
pos = candidates.index(temp[0])
if not flag:
break
tree[-1] = candidates[pos]
for i in range(len(temp_c)):
if sum(tree) < target:
tree.append(temp_c[i])
if sum(tree) < target:
for i in range(len(temp_c)):
if sum(tree) < target:
tree.append(temp_c[i])
result = list(result)
for i in range(len(result)):
result[i] = list(result[i])
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python