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

मी 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.