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 {
bool search(const string &s, int cur, int target, int sum, int acc) {
if (sum > target) {
return false;
}
if (cur == s.size()) {
return (sum + acc) == target;
}
bool valid = false;
valid = valid || search(s, cur + 1, target, sum + (acc * 10 + s[cur] - '0'), 0);
valid = valid || search(s, cur + 1, target, sum, acc * 10 + s[cur] - '0');
return valid;
}
public:
int punishmentNumber(int n) {
int ans = 0;
for (int i = 1; i <= n; i++) {
int x = i * i;
string s = to_string(x);
if (search(s, 0, i, 0, 0)) {
cout << i << endl;
ans += x;
}
}
return ans;
}
};
|