Leetcode NO.279 Perfect Squares

来源:互联网 发布:全面战争多核优化 编辑:程序博客网 时间:2024/06/05 16:11

本题题目要求如下:

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

本题思路还是比较直接的,花了20多分钟就解出来了,就是用BFS解,就拿13举例,13是root,然后13 - 3 * 3 = 4, 13 - 2 * 2 = 9, 13 - 1 * 1 = 12,

4, 9, 12就是root的三个child,是第二层;再下面一层,4 - 2 * 2 = 0, 4 - 1 * 1 = 3,4的child是0和3,此时已经可以结束了,因为已经出线了0,所以返回2,就是root到这个0之间只有两层。。

然后详细代码如下:

class Solution {public:    int numSquares(int n) {        queue<int> currentLevel;        queue<int> nextLevel;        currentLevel.push(n);        int level = 1;        while (!currentLevel.empty()) {            int val = currentLevel.front();            currentLevel.pop();            for (int i = (int)sqrt(val); i >= 1; --i) {                int tmp = val - i * i;                if (tmp == 0) {                    return level;                }                nextLevel.push(val - i * i);            }            if (currentLevel.empty()) {                swap(currentLevel, nextLevel);                ++level;            }        }    }};

 

0 0
原创粉丝点击