头图

perfect square

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

Given an integer n, return the minimum number of perfect squares whose sum is n.

A perfect square 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 squares, but 3 and 11 are not.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/perfect-squares/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Dynamic Programming

Through dynamic programming, first, initialize a dp array to record the minimum number of powers and accumulations that each bit can have, and then initialize the value of each bit to the maximum value for subsequent comparisons, and then the core The logic is the following traversal process:

  • The power sum of the i-th bit can be composed of the step i -> j j plus the number of steps of the power sum of the j j bits, and then the smaller value of each judgment is compared as the number of the i-th bit.

Explanation: After reading the analysis and solution process based on mathematical logic on the Internet, the focus is on analysis. It’s simple.

 public class LeetCode_279 {
    /**
     * 动态规划
     *
     * @param n
     * @return
     */
    public static int numSquares(int n) {
        // 记录每一位的可以有最少多少个乘方和累加的个数
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            // 把每一个个数都初始化为最大值
            dp[i] = Integer.MAX_VALUE;
        }
        // 从1开始遍历
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j * j <= i; j++) {
                if (i >= j * j) {
                    // 这里的逻辑是第i位的乘方和组成可以由 i -> j * j 这一步 加上 j * j 位的乘方和的步数组成,然后比较每一次判断较小值作为第i位的个数
                    dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
                }
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        // 测试用例一,期望输出: 3 (由 4 + 4 + 4 得到)
        System.out.println(numSquares(12));

        // 测试用例二,期望输出: 2 (由 4 + 9 得到)
        System.out.println(numSquares(13));
    }
}
【Daily Message】 Learning enriches people's knowledge, knowledge improves people's talents, and enables people to create performance.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!