2698. Find the Punishment Number of an Integer

DFS

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
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int punishmentNumber(int n) {
int result = 0;

for (int i = 1; i <= n; i++) {
if (match(i)) {
result += i * i;
}
}

return result;
}

private boolean match(int num) {
int product = num * num;
String productStr = String.valueOf(product);

// 分割成多个,和为 num
return dfs(productStr, 0, 0, num);
}

private boolean dfs(String productStr, int startIndex, int subSum, int targetSum) {
if (subSum > targetSum) {
return false;
}

if (startIndex == productStr.length()) {
return subSum == targetSum;
}

int num = 0;
for (int endIndex = startIndex; endIndex < productStr.length(); endIndex++) {
num = num * 10 + (productStr.charAt(endIndex) - '0');
if (dfs(productStr, endIndex + 1, subSum + num, targetSum)) {
return true;
}
}

return false;
}
}

References

2698. Find the Punishment Number of an Integer