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
| class Solution { public int punishmentNumber(int n) { int res = 0; for (int i = 1; i <= n; ++i) { if (check(i)) res += i * i; } return res; }
private boolean check(int x) { path.clear(); return dfs(x, String.valueOf(x * x), 0); }
Deque<String> path = new LinkedList<>(); private boolean dfs(int x, String str, int index) { if (index == str.length()) { int sum = 0; for (String s : path) sum += Integer.parseInt(s); return sum == x; } for (int i = index; i < str.length(); ++i) { String sub = str.substring(index, i + 1); path.offerLast(sub); if (dfs(x, str, i + 1)) return true; path.pollLast(); } return false; } }
|