Skip to content

Latest commit

 

History

History
127 lines (100 loc) · 2.88 KB

File metadata and controls

127 lines (100 loc) · 2.88 KB

中文文档

Description

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.

 

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

 

Constraints:

  • 1 <= n <= 104

Solutions

For dynamic programming, define dp[i] to represent the least number of perfect square numbers that sum to i.

Python3

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [0 for i in range(n + 1)]
        for i in range(1, n + 1):
            j, mi = 1, 0x3f3f3f3f
            while j * j <= i:
                mi = min(mi, dp[i - j * j])
                j += 1
            dp[i] = mi + 1
        return dp[n]

Java

class Solution {
    public int numSquares(int n) {
        List<Integer> ans = new ArrayList<>();
        ans.add(0);
        while (ans.size() <= n) {
            int m = ans.size(), val = Integer.MAX_VALUE;
            for (int i = 1; i * i <= m; i++) {
                val = Math.min(val, ans.get(m - i * i) + 1);
            }
            ans.add(val);
        }
        return ans.get(n);
    }
}

TypeScript

function numSquares(n: number): number {
    let dp = new Array(n + 1).fill(0);
    for (let i = 1; i <= n; ++i) {
        let min = Infinity;
        for (let j = 1; j * j <= i; ++j) {
            min = Math.min(min, dp[i - j * j]);
        }
        dp[i] = min + 1;
    }
    return dp.pop();
};

Go

/*
 * @lc app=leetcode.cn id=279 lang=golang
 * 动态规划的思路,状态转移方程:dp[n] = min(dp[n-1*1]+1, dp[n-2*2]+1, ..., dp[n-k*k]+1), ( 0< k*k <=n )
 */
func numSquares(n int) int {
	if n <= 0 {
		return 0
	}
	dp := make([]int, n+1) // 多申请了一份整形,使代码更容易理解, dp[n] 就是 n 的完全平方数的求解
	for i := 1; i <= n; i++ {
		dp[i] = i // 初始值 dp[n] 的最大值的解,也是最容易求的解
		for j := 0; j*j <= i; j++ {
			dp[i] = minInt(dp[i-j*j]+1, dp[i])
		}
	}
	return dp[n]
}

func minInt(x, y int) int {
	if x < y {
		return x
	}
	return y
}

...