Skip to content

Commit 2560ba7

Browse files
committed
recursion problems added.
1 parent 64b27ac commit 2560ba7

File tree

3 files changed

+122
-0
lines changed

3 files changed

+122
-0
lines changed

recursion/coin_change.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
3+
4+
Example 1:
5+
6+
Input: coins = [1, 2, 5], amount = 11
7+
Output: 3
8+
Explanation: 11 = 5 + 5 + 1
9+
Example 2:
10+
11+
Input: coins = [2], amount = 3
12+
Output: -1
13+
14+
Note: You may assume that you have an infinite number of each kind of coin.
15+
Solution 1 using dp O(n^2)
16+
Solution 2 using dfs or bfs with pruning
17+
"""
18+
19+
from typing import List
20+
21+
22+
class Solution:
23+
def coinChange(self, coins: List[int], amount: int) -> int:
24+
25+
self.ans = float('inf')
26+
27+
# Start searching from the biggest coin
28+
coins.sort(reverse=True)
29+
self.dfs(coins, amount, 0)
30+
return -1 if self.ans == float('inf') else self.ans
31+
32+
def dfs(self, coins, amount, prev_count):
33+
"""
34+
Recursive DFS function to seach valid coins combination.
35+
First is to use greedy method find out a potential-best solution.
36+
Then start to search the second biggest coin with pruning when the coins number >= the potential-best solution.
37+
38+
Args:
39+
coins: coins list from which we pick coins into combination
40+
amount: target amount
41+
prev_count: number of coins picked before this round
42+
43+
"""
44+
# Set up stop condtion
45+
if len(coins) == 0:
46+
return
47+
48+
if amount % coins[0] == 0:
49+
# Update potential answer
50+
self.ans = min(self.ans, prev_count + amount // coins[0])
51+
else:
52+
for k in range(amount // coins[0], -1, -1):
53+
# Set up pruning condtion
54+
if prev_count + k >= self.ans:
55+
break
56+
self.dfs(coins[1:], amount - k * coins[0], prev_count + k)
57+
58+
59+
solution = Solution()
60+
assert solution.coinChange([1, 2, 5], 11) == 3, "Test case 1 failed"
61+
assert solution.coinChange([1, 2, 5], 13) == 4, "Test case 2 failed"

recursion/generate_paranthesis.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import collections
2+
from typing import List
3+
4+
5+
class Solution:
6+
def generateParenthesisUsingBFS(self, n: int) -> List[str]:
7+
ans = []
8+
# For element in queue, it means (pre-string, left, right)
9+
queue = collections.deque([('', n, n)])
10+
while queue:
11+
pre, left, right = queue.popleft()
12+
if right == 0:
13+
ans.append(pre)
14+
if left:
15+
queue.append((pre + '(', left - 1, right))
16+
if right > left:
17+
queue.append((pre + ')', left, right - 1))
18+
return ans
19+
20+
def generateParenthesis(self, n: int) -> List[str]:
21+
ans = []
22+
23+
def helper(openB, closeB, brackets):
24+
if closeB == 0:
25+
ans.append(brackets)
26+
if openB > 0: # add open bracket
27+
helper(openB - 1, closeB, brackets + "(")
28+
if closeB > openB:
29+
helper(openB, closeB - 1, brackets + ")")
30+
helper(n, n, "")
31+
return ans
32+
33+
34+
solution = Solution()
35+
print(solution.generateParenthesis(3))
36+
print(solution.generateParenthesisUsingBFS(3))

recursion/permutations.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def __init__(self):
6+
self._ans = []
7+
self._total = 0
8+
9+
def generate_permutations(self, index, nums):
10+
if index == self._total:
11+
self._ans.append(nums.copy())
12+
return
13+
for i in range(index, self._total):
14+
nums[index], nums[i] = nums[i], nums[index]
15+
self.generate_permutations(index + 1, nums)
16+
nums[index], nums[i] = nums[i], nums[index]
17+
18+
def permute(self, numbers: List[int]) -> List[List[int]]:
19+
self._total = len(numbers)
20+
self.generate_permutations(0, numbers)
21+
return self._ans
22+
23+
24+
solution = Solution()
25+
print(solution.permute([1, 2, 3, 4]))

0 commit comments

Comments
 (0)