# coding=utf-8 # 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. # 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 10,1,2,7,6,1,5 and target 8, # A solution set is: # [1, 7] # [1, 2, 5] # [2, 6] # [1, 1, 6]
# DFS class Solution(): def combinationSum2(self, x, target): x.sort() res = [] self.dfs(res, x, target-0, 0, []) return res def dfs(self, res, x, diff, start, path): if diff == 0 and path not in res: # 加上 path not in res 来去重 res.append(path) elif diff > 0: for j in range(start, len(x)): # 改为 self.dfs(res, x, diff-x[j], j, path+[x[j]]) 则 子数组 内 可含有 下标相同的元素 self.dfs(res, x, diff-x[j], j+1, path+[x[j]]) if __name__ == "__main__": assert Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8) == [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句