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 26
| class Solution { public: int numSquares(int n) { vector<int> v; int t = 1; while (t * t <= n) { v.emplace_back(t * t); ++t; } int m = v.size(); vector<vector<int>> f(m + 1, vector<int>(n + 1, n)); f[0][0] = 0; for (int i = 1; i <= m; ++i) { int x = v[i - 1]; for (int j = 0; j <= n; ++j) { f[i][j] = f[i - 1][j]; for (int k = 1; k * x <= j; ++k) { if (f[i - 1][j - k * x] != n) { f[i][j] = min(f[i][j], f[i - 1][j - k * x] + k); } } } } return f[m][n]; } };
|