Skip to content

Latest commit

 

History

History
139 lines (110 loc) · 2.82 KB

File metadata and controls

139 lines (110 loc) · 2.82 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] * (n + 1)
        for i in range(1, n + 1):
            j, mi = 1, float('inf')
            while j * j <= i:
                mi = min(mi, dp[i - j * j])
                j += 1
            dp[i] = mi + 1
        return dp[-1]

Java

class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; ++i) {
            int mi = Integer.MAX_VALUE;
            for (int j = 1; j * j <= i; ++j) {
                mi = Math.min(mi, dp[i - j * j]);
            }
            dp[i] = mi + 1;
        }
        return dp[n];
    }
}

C++

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1);
        for (int i = 1; i <= n; ++i) {
            int mi = 100000;
            for (int j = 1; j * j <= i; ++j) {
                mi = min(mi, dp[i - j * j]);
            }
            dp[i] = mi + 1;
        }
        return dp[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

func numSquares(n int) int {
	dp := make([]int, n+1)
	for i := 1; i <= n; i++ {
		mi := 100000
		for j := 1; j*j <= i; j++ {
			mi = min(mi, dp[i-j*j])
		}
		dp[i] = mi + 1
	}
	return dp[n]
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

...