279:完全平方数

This commit is contained in:
huangge1199 2021-06-11 09:24:10 +08:00
parent ba1b284ff8
commit 7ed6e8f206
3 changed files with 91 additions and 1 deletions

View File

@ -0,0 +1,61 @@
//给定正整数 n找到若干个完全平方数比如 1, 4, 9, 16, ...使得它们的和等于 n你需要让组成和的完全平方数的个数最少
//
// 给你一个整数 n 返回和为 n 的完全平方数的 最少数量
//
// 完全平方数 是一个整数其值等于另一个整数的平方换句话说其值等于一个整数自乘的积例如149 16 都是完全平方数 3 11 不是
//
//
//
//
// 示例 1
//
//
//输入n = 12
//输出3
//解释12 = 4 + 4 + 4
//
// 示例 2
//
//
//输入n = 13
//输出2
//解释13 = 4 + 9
//
//
// 提示
//
//
// 1 <= n <= 104
//
// Related Topics 广度优先搜索 数学 动态规划
// 👍 906 👎 0
package leetcode.editor.cn;
//279:完全平方数
public class PerfectSquares {
public static void main(String[] args) {
//测试代码
Solution solution = new PerfectSquares().new Solution();
System.out.println(solution.numSquares(12));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int numSquares(int n) {
int[] counts = new int[n + 1];
for (int i = 1; i <= n; i++) {
int min = Integer.MAX_VALUE;
int max = (int)Math.sqrt(i);
for (int j = 1; j <= max; j++) {
min = Math.min(min, counts[i - j * j]);
}
counts[i] = min+1;
}
return counts[n];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,29 @@
<p>给定正整数 <em>n</em>,找到若干个完全平方数(比如 <code>1, 4, 9, 16, ...</code>)使得它们的和等于<em> n</em>。你需要让组成和的完全平方数的个数最少。</p>
<p>给你一个整数 <code>n</code> ,返回和为 <code>n</code> 的完全平方数的 <strong>最少数量</strong></p>
<p><strong>完全平方数</strong> 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,<code>1</code><code>4</code><code>9</code><code>16</code> 都是完全平方数,而 <code>3</code><code>11</code> 不是。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>n = <code>12</code>
<strong>输出:</strong>3
<strong>解释:</strong><code>12 = 4 + 4 + 4</code></pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>n = <code>13</code>
<strong>输出:</strong>2
<strong>解释:</strong><code>13 = 4 + 9</code></pre>
 
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>广度优先搜索</li><li>数学</li><li>动态规划</li></div></div>\n<div><li>👍 903</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long