求一个整数的惩罚数
难度:
标签:
题目描述
Given a positive integer n
, return the punishment number of n
.
The punishment number of n
is defined as the sum of the squares of all integers i
such that:
1 <= i <= n
- The decimal representation of
i * i
can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equalsi
.
Example 1:
Input: n = 10 Output: 182 Explanation: There are exactly 3 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1 - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. Hence, the punishment number of 10 is 1 + 81 + 100 = 182
Example 2:
Input: n = 37 Output: 1478 Explanation: There are exactly 4 integers i that satisfy the conditions in the statement: - 1 since 1 * 1 = 1. - 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. - 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. - 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6. Hence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478
Constraints:
1 <= n <= 1000
代码结果
运行时间: 46 ms, 内存: 16.0 MB
/*
* 思路:
* 1. 使用IntStream从1到n进行遍历。
* 2. 对于每个i,计算i*i,并检查其是否满足条件。
* 3. 将满足条件的i*i累加。
* 4. 返回累加的惩罚数之和。
*/
import java.util.stream.IntStream;
public class Solution {
public int punishmentNumber(int n) {
return IntStream.rangeClosed(1, n)
.map(i -> i * i)
.filter(square -> canBeSplit(String.valueOf(square), (int) Math.sqrt(square)))
.sum();
}
private boolean canBeSplit(String s, int target) {
return canBeSplitHelper(s, target, 0, 0);
}
private boolean canBeSplitHelper(String s, int target, int currentSum, int start) {
if (start == s.length()) {
return currentSum == target;
}
for (int i = start; i < s.length(); i++) {
int num = Integer.parseInt(s.substring(start, i + 1));
if (canBeSplitHelper(s, target, currentSum + num, i + 1)) {
return true;
}
}
return false;
}
}
解释
方法:
首先,这个题解通过预计算的方法解决问题,即预先计算了所有可能的 n (从 1 到 1000) 的惩罚数,并将结果存储在数组 ans 中。对于每个 n,计算 n 的平方并转换为字符串 sq。然后,使用一个递归函数 dfs 来尝试所有可能的连续子字符串分割方式,查看这些子字符串的整数和是否等于 n。如果存在这样的分割方式,那么该 n 的惩罚数就是 n 的平方;否则为 0。最后,累加数组 ans 中的值,以便直接通过索引快速回答任何小于等于 1000 的 n 的询问。
时间复杂度:
O(n * 2^k)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么选择预计算所有可能的 n 的惩罚数而不是在每次查询时动态计算?
▷🦆
在递归函数 dfs 中,递归的终止条件是 `start == len(sq)`,这意味着什么?如何确保所有子字符串都被考虑?
▷🦆
您提到的分割点可能性为 `2^9`,这是如何计算得出的?请解释分割点选择的逻辑。
▷