Leetcode-279

Perfect Squares

Time complexity: $O(n^\frac{3}{2})$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <numeric>

class Solution {
public:
    int numSquares(int n) {
        int dp[10001];
        std::iota(dp, dp + n + 1, 0);
        
        int b = 1;
        while (true) {
            ++b;
            int s = b * b;
            if (s > n) {
                break;
            }
            for (int i = s; i <= n; ++i) {
                dp[i] = std::min(dp[i], dp[i - s] + 1);
            }
        }
        
        return dp[n];
    }
};

Leetcode-279

Licensed under CC BY-NC-SA 4.0