Leetcode 279. Perfect Squares

Problem

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Algorithm

Dynamic programming (DP).

Code

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [0] * (n + 1)
        for i in range(n+1):
            dp[i] = i 
        for i in range(1, 101):
            if i * i > n: break
            for j in range(1, n+1):
                if j >= i * i and dp[j] > dp[j - i * i] + 1:
                    dp[j] = dp[j - i * i] + 1
        return dp[n] 

你可能感兴趣的:(leetcode,算法,解题报告)