Tensorum
YouTubeশেখা শুরু করুন
LeetCode 279 · Unbounded Knapsack

Perfect Squares

LeetCode 279 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

dp[x] = 1 + min(dp[x − s]) over squares s ≤ x.

মাঝারিMathDynamic ProgrammingBreadth-First SearchKnapsack ProblemComplete Knapsack
LeetCode-এ খুলুন ↗

আমি 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. 1

    List the squares 1, 4, 9, … up to n.

  2. 2

    dp[0] = 0.

  3. 3

    For each x from 1 to n, try every square that fits and keep the minimum.

  4. 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.