We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
出处 LeetCode 算法第279题 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 示例 1: 输入: n = 12 输出: 3 解释: 12 = 4 + 4 + 4. 示例 2: 输入: n = 13 输出: 2 解释: 13 = 4 + 9.
出处 LeetCode 算法第279题
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12 输出: 3 解释: 12 = 4 + 4 + 4. 示例 2:
输入: n = 13 输出: 2 解释: 13 = 4 + 9.
如果一个数本身不是完全平方数,它一定是其他两个比它小的数的和,只要组成这两个数的完全平方数最少即可。所以可以采用动态规划的思路
/** * @param {number} n * @return {number} * */ var numSquares = function (n) { var dp = [0]; for (var i = 1; i <= n; i++) { if (isSquare(i)) { dp[i] = 1; } else { var j = 1; var min = Number.MAX_VALUE; while (j <= Math.ceil(i / 2)) { if (dp[j] + dp[i - j] < min) { min = dp[j] + dp[i - j]; } j++; } dp[i] = min; } } return dp[n]; }; // 判断是否是完全平方数 var isSquare = function (number) { var temp = parseInt(Math.sqrt(number)); if (temp * temp == number) { return true; } return false; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
如果一个数本身不是完全平方数,它一定是其他两个比它小的数的和,只要组成这两个数的完全平方数最少即可。所以可以采用动态规划的思路
解答
The text was updated successfully, but these errors were encountered: