Perfect Squares
LeetCode 279 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.
நான் Perfect Squares (LeetCode 279) ஐ இப்படித் தீர்த்தேன் — Unbounded Knapsack பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Treat each perfect square as a coin you can use as often as you like, and ask for the fewest coins that add up to n. dp[x] is the fewest squares for x, built from dp[x − s] + 1 over every square s ≤ x.
Approach
- 1
List the squares 1, 4, 9, … up to n.
- 2
dp[0] = 0.
- 3
For each x from 1 to n, try every square that fits and keep the minimum.
- 4
Return dp[n].
நான் எப்படித் தீர்த்தேன்
Tabulation over nPythonO(n√n) time · O(n) space
class Solution:
def numSquares(self, n: int) -> int:
squares =[i**2 for i in range(1,int(math.sqrt(n))+1)]
# def dfs(cur_num):
# if cur_num in squares:
# return 1
# min_count=float("inf")
# for square in squares:
# if square>cur_num:
# break
# cur_count=dfs(cur_num-square)+1
# min_count=min(min_count,cur_count)
# return min_count
# return dfs(n)
dp=[float("inf")]*(n+1)
dp[0]=0
for cur_num in range(1,n+1):
min_count=float("inf")
for square in squares:
if square>cur_num:
break
cur_count=dp[cur_num-square]+1
min_count=min(min_count,cur_count)
dp[cur_num]=min_count
return dp[n]Perfect Squares — அடிக்கடி கேட்கப்படும் கேள்விகள்
Perfect Squares பின்னாலுள்ள intuition என்ன?
Treat each perfect square as a coin you can use as often as you like, and ask for the fewest coins that add up to n. dp[x] is the fewest squares for x, built from dp[x − s] + 1 over every square s ≤ x.
Perfect Squares (LeetCode 279) ஐ எப்படித் தீர்ப்பது?
1. List the squares 1, 4, 9, … up to n. 2. dp[0] = 0. 3. For each x from 1 to n, try every square that fits and keep the minimum. 4. Return dp[n].
Perfect Squares இன் time மற்றும் space complexity என்ன?
Time: O(n · √n). Space: O(n). (Accepted approach: Tabulation over n.)
Perfect Squares இல் பொதுவான தவறுகள் என்ன?
Break out of the squares loop once a square exceeds x. Lagrange's four-square theorem caps the answer at 4 — a neat sanity check.