leetcode 完全平方数 中等

时间:2021-08-17
本文章向大家介绍leetcode 完全平方数 中等,主要包括leetcode 完全平方数 中等使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

① dp:完全背包,没啥好说的

② bfs:有很重要的一点,在 bfs 中的循环中提前判断是否到达 0,能够减少很多计算。是减少很多很多!!!

③数学题:不记录。

dp:

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, INT_MAX);   // 组成 i 所用的最少的数个数
        dp[0] = 0;
        for(int i = 1; i <= n; ++ i) {
            for(int j = 1; j * j <= i; ++ j) {
                dp[i] = min(dp[i], dp[i - j * j] + 1);
            }
        }
        return dp[n];
    }
};

bfs:

class Solution {
public:
    int numSquares(int n) {
        queue<pair<int, int>> que;
        que.push({n, 0});
        vector<bool> tag(n + 1, false);
        while(!que.empty()) {
            auto front = que.front(); que.pop();
            for(int i = sqrt(front.first); i >= 1; -- i) {
                if(front.first == i * i) return front.second + 1;      // 可少跑很多数据
                if(tag[front.first - i * i]) continue;     // 可少跑很多数据
                tag[front.first - i * i] = true;
                que.push({front.first - i * i, front.second + 1});
            }
        }
        return -1;
    }
};

 

原文地址:https://www.cnblogs.com/rookie-acmer/p/15154468.html