Leetcode NO.279 Perfect Squares

本题题目要求如下:

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;
            }
        }
    }
};

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值