forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathk_sum_ii.py
28 lines (26 loc) · 879 Bytes
/
k_sum_ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding: utf-8 -*-
class Solution:
"""
@param A: An integer array.
@param k: A positive integer (k <= length(A))
@param target: Integer
@return a list of lists of integer
"""
def kSumII(self, A, k, target):
# write your code here
self.ret = []
self.dfs(A, k, target, 0, [])
return self.ret
def dfs(self, A, k, target, index, candidates):
if (target == 0) and (k == 0):
self.ret.append(candidates)
return None
if (len(A) == index) or (target < 0) or (k < 0):
return None
# 跳过A[index]
self.dfs(A, k, target, index + 1, candidates)
# 保留A[index]
new_candidates = []
new_candidates.extend(candidates)
new_candidates.append(A[index])
self.dfs(A, k - 1, target - A[index], index + 1, new_candidates)