Problem Description
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 equals i.
Key Insights
- The problem requires checking each integer i from 1 to n.
- For each i, compute i * i and check if it can be partitioned into substrings that add up to i.
- This involves generating all possible partitions of the string representation of i * i.
- The punishment number is the sum of squares of valid integers.
Space and Time Complexity
Time Complexity: O(n * m^2) where n is the input number and m is the number of digits in i * i. Space Complexity: O(m) for storing the partitions.
Solution
The solution involves iterating through all integers from 1 to n, calculating their squares, and checking if those squares can be broken down into parts that sum to the integer itself. We can use a backtracking approach to explore all substring partitions and check their sums against the integer.