279. 完全平方数

279. 完全平方数

给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。

完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,149 和 16 都是完全平方数,而 3 和 11 不是。

 

示例 1:

输入:n = 12
输出:3 
解释:12 = 4 + 4 + 4

示例 2:

输入:n = 13
输出:2
解释:13 = 4 + 9
 

提示:

  • 1 <= n <= 104

解题思路:

 

 

 

 

 1 #include <iostream>
 2 #include <queue>
 3 #include <math.h>
 4 using namespace std;
 5 
 6 /*
 7 输入:n = 12
 8 输出:3
 9 解释:12 = 4 + 4 + 4
10 */
11 class Solution
12 {
13 public:
14     int numSquares(int n) {
15         if (n <= 0) {
16             return 0;
17         }
18         queue<int> q;
19         q.push(n);
20         int num = 0;
21         while (!q.empty()) {
22             int size = q.size();
23             for (int i = 0; i < size; i++) {
24                 int now = q.front();
25                 q.pop();
26                 for (int j = sqrt(now); j > 0; j--) {
27                     if (now == j * j) {
28                         num++;
29                         return num;
30                     } else {
31                         q.push(now - j * j);
32                     }
33                 }
34             }
35             num++;
36         }
37         return 0;
38     }
39 };
40 
41 int main()
42 {
43     Solution *test = new Solution();
44     int n = 12;
45     cout << test->numSquares(n) << endl;
46     system("pause");
47     return 0;
48 }

 稍微改动下:

 

 

 1 class Solution
 2 {
 3 public:
 4     int numSquares(int n) {
 5         if (n <= 0) {
 6             return 0;
 7         }
 8         queue<int> q;
 9         q.push(n);
10         int num = 0; // BFS遍历层数
11         while (!q.empty()) {
12             int size = q.size(); // BFS遍历每层的元素个数
13             for (int i = 0; i < size; i++) {
14                 int now = q.front();
15                 q.pop();
16                 cout << now << " ";
17                 for (int j = 1; j <= sqrt(now); j++) {
18                     int next = now - j * j;
19                     if (next == 0) {
20                         num++;
21                         cout << endl;
22                         return num;
23                     } else {
24                         q.push(next);
25                     }
26                 }
27             }
28             cout << endl;
29             num++;
30         }
31         return 0;
32     }
33 };

 

posted @ 2022-03-21 00:20  跳动的休止符  阅读(212)  评论(0)    收藏  举报