forked from Srinivas11789/AlgorithmNuggets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum.py
More file actions
63 lines (49 loc) · 2.05 KB
/
sum.py
File metadata and controls
63 lines (49 loc) · 2.05 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
### Pending...
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
### Works for smaller target values
# Sorted Logic
candidates = sorted(candidates)
result = []
# Iterate through each candidate
n = len(candidates)
ans = []
for i in range(n):
# Repeated Condition
while sum(ans) < target:
ans.append(candidates[i])
if sum(ans) == target:
if ans not in result:
result.append(ans)
ans = []
# Combination of other numbers
if i+1 < n-1:
for j in range(i+1,n):
print candidates[i],candidates[j]
cur = candidates[i]+candidates[j]
if target-cur in candidates:
array = sorted([candidates[i], candidates[j], target-cur])
if array not in result:
result.append(array)
if target-cur == 0:
array = sorted([candidates[i], candidates[j]])
if array not in result:
result.append(array)
else:
j = n-1
print candidates[i],candidates[j]
cur = candidates[i]+candidates[j]
if target-cur in candidates:
array = sorted([candidates[i], candidates[j], target-cur])
if array not in result:
result.append(array)
if target-cur == 0:
array = sorted([candidates[i], candidates[j]])
if array not in result:
result.append(array)
return result