Catalogue
Count
279. Perfect Squares
Solution1. DP - TLE
- Time O($n\sqrt{n}$), Space: O(n)
- have no idea why works in python2, but TLE in python3
1 | class Solution: |
Solution2. BFS
- Consider a graph which consists of number 0, 1,…,n as its nodes.
- Node j is connected to node i via an edge if and only if either j = i + (a perfect square number) or i = j + (a perfect square number). Starting from node 0, do the breadth-first search.
- If we reach node n at step m, then the least number of perfect square numbers which sum to n is m. Here since we have already obtained the perfect square numbers, we have actually finished the search at step 1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class Solution:
def numSquares(self, n):
cans = []
i = 1
while i * i <= n:
cans.append(i * i)
i += 1
queue = [n]
level = 0
while queue:
level += 1
nqueue = set()
for remain in queue:
for can in cans:
if can == remain:
return level
if can > remain:
break
nqueue.add(remain-can)
queue = list(nqueue)
322. Coin Change
1 | class Solution(object): |
Count
518. Coin Change 2
- Why use for loop in this order??? coin first, then amount?
1
2
3
4
5
6
7
8class Solution(object):
def change(self, amount, coins):
dp = [0] * (amount+1)
dp[0] = 1
for coin in coins:
for i in range(coin, amount+1):
dp[i] += dp[i-coin]
return dp[-1]