Skip to content

Commit 3735871

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent 5348ac3 commit 3735871

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Leetcode Python Solution
2-
1. This is my Python solution on Leetcode. The question is at `problems/the-file-name/`. For example, `merge-sorted-array.py`'s question is at `https://leetcode.com/problems/merge-sorted-array/`.
2+
1. This is my Python (2.7) solution on Leetcode. The question is at `problems/the-file-name/`. For example, `merge-sorted-array.py`'s question is at `https://leetcode.com/problems/merge-sorted-array/`.
33

44
2. I really take time tried to make the best solution or explaination.
55
Because I wanted to help others like me.

problems/combination-sum-iii.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
If you haven't seen [this problem](https://leetcode.com/problems/combinations/), I suggest you do that first!
3+
And here is the [explaination](https://leetcode.com/problems/combinations/discuss/387753) for that problem.
4+
5+
This problem is basically the same as [that problem](https://leetcode.com/problems/combinations/) with its N=9.
6+
The difference is we have to find the combination that sum up as N.
7+
So all we have to do is change the condition of [0]. And the condition for backtracking [1].
8+
"""
9+
class Solution(object):
10+
def combinationSum3(self, K, N):
11+
answer = []
12+
ans = []
13+
first = 1
14+
total = 0
15+
while True:
16+
if len(ans)==K and total==N: #[0]
17+
answer.append(ans[:])
18+
19+
if len(ans)==K or total>N or first>9: #[1]
20+
if not ans: return answer
21+
first = ans.pop() #backtrack
22+
total-=first
23+
first+=1
24+
else:
25+
ans.append(first)
26+
total+=first
27+
first+=1

0 commit comments

Comments
 (0)