Leetcode problem solution 279-perfect square number

Problem Description

Given a positive integer n, find several perfect square numbers (such as 1, 4, 9, 16, …) so that their sum is equal to n. You need to minimize the number of perfect squares that make up the sum.

Give you an integer n, and return the minimum number of perfect squares whose sum is n.

A perfect square number is an integer whose value is equal to the square of another integer; in other words, its value is equal to the product of an integer multiplied by itself. For example, 1, 4, 9, and 16 are all perfect square numbers, but 3 and 11 are not.

Example 1:

输入:n = 12
输出:3 
解释:12 = 4 + 4 + 4

Example 2:

输入:n = 13
输出:2
解释:13 = 4 + 9

prompt:

1 <= n <= 104

Problem-solving ideas:

This problem is similar to the Fibonacci number problem. Like the Fibonacci number, we can use a more efficient method to calculate the solution instead of simple recursion.

One way to solve the problem of stack overflow in recursion is to use dynamic programming (DP) technology, which is based on the idea of ​​reusing the results of intermediate solutions to calculate the final solution.

To calculate the value of numSquares(n), first calculate all the values ​​before n, that is, numSquares(nk), where k is the square number. If we have kept the solution of the number nk somewhere, then there is no need to use recursion Calculation.

First initialize the array dp with length n+1, each position is 0.
If n is 0, the result is 0.
Traverse the array with the subscript i, and update the current number to the largest result each time, that is dp[i]=i, such as i=4, the worst result is 4=1+1+1+1, that is, 4 digital
dynamic transfer equations are: dp[i] = MIN(dp[i], dp[i -j * j] + 1), i represents the current number, j j represents the square number
Time complexity: O(n
sqrt(n))O(n∗sqrt(n)), sqrt is the square root

Implementation code

class Solution {
    
    
    public int numSquares(int n) {
    
    
        //dp[i]代表数i的完全平方数的最少数量
        int dp[]=new int[n+1];
        for(int i=1;i<=n;i++){
    
    
            //初始化为i,最坏情况下的完全平方数的个数
            dp[i]=i;
            for(int j=0;i-j*j>=0;j++){
    
    
                //比较当前统计的完全平方数的个数,与数i-j*j+j*j这种情况下的完全平方数的个数
                dp[i]=Math.min(dp[i],dp[i-j*j]+1);
            }
        }
        return dp[n];
    }
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/114488619