LC.P2698[求一个整数的惩罚数]

方法一:枚举+DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int punishmentNumber(int n) {
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = i * i;
if (check(x + "", 0, i)) ans += x;
}
return ans;
}

private boolean check(String s, int i, int target) {
int m = s.length();
if (i >= m) return target == 0;
int x = 0;
for (int j = i; j < m; ++j) {
x = x * 10 + (s.charAt(j) - '0');
if (x > target) return false;
if (check(s, j + 1, target - x)) return true;
}
return false;
}
}