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.