大家好,我是晴天学长,这是一道常见方案数演变而来的题目,重点是要用已知条件去不断的剪枝操作哦!
public class 求一个整数的惩罚数 {
public static void main(String[] args) {
System.out.println(Solution.punishmentNumber(1000));
}
static class Solution {
public static int punishmentNumber(int n) {
int ans = 0;
for (int i = 1; i <= n; i++) {
int t = i * i;
if (dfs(t + "", 0, i)) {
ans += t;
}
}
return ans;
}
private static boolean dfs(String str, int index, int target) {
if (index == str.length()) {
return target == 0;
}
for (int i = index; i < str.length(); i++) {
int curr = Integer.parseInt(str.substring(index, i + 1));
// 减枝
if (target - curr < 0) {
break;
}
if (dfs(str, i + 1, target - curr)) {
return true;
}
}
return false;
}
}
}