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 27 28
| class Solution { public: int numSquares(int n) { queue<int> q; set<int> s; q.push(n); int ct = 0; while(q.size()) { ct++; int sz = q.size(); for(int i = 0; i < sz; ++i){ int w = q.front(); q.pop(); for(int j = 1; j * j <= w; ++j) { int x = w - j * j; if(!s.count(x)) { if(x == 0) return ct; q.push(x); s.insert(x); } } }
} return -1; } };
|