Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

279. Perfect Squares #236

Open
Tcdian opened this issue Jun 28, 2020 · 1 comment
Open

279. Perfect Squares #236

Tcdian opened this issue Jun 28, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 28, 2020

279. Perfect Squares

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

Example 1

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

Example 2

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 28, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} n
 * @return {number}
 */
var numSquares = function(n) {
    const dp = Array.from(new Array(n + 1), (val, index) => index);
    for (let i = 1; i <= n; i++) {
        let j = Math.floor(Math.sqrt(i));
        while (j > 0) {
            dp[i] = Math.min(dp[i - j * j] + 1, dp[i]);
            j--;
        }
    }
    return dp[n];
};
  • TypeScript Solution
function numSquares(n: number): number {
    const dp: number[] = Array.from(new Array(n + 1), (val, index) => index);
    for (let i = 1; i <= n; i++) {
        let j = Math.floor(Math.sqrt(i));
        while (j > 0) {
            dp[i] = Math.min(dp[i - j * j] + 1, dp[i]);
            j--;
        }
    }
    return dp[n];
};

@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant