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

完全平方数 #202

Open
louzhedong opened this issue Feb 3, 2020 · 0 comments
Open

完全平方数 #202

louzhedong opened this issue Feb 3, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant