2698. Find the Punishment Number of an Integer
UnknownView on LeetCode
Time: O(n * 2^d)
Space: O(d)
Problem Overview
Find the Punishment Number of an Integer (Unknown) asks you to solve a structured algorithmic task. This is a common Math / Backtracking pattern in coding interviews. For each i check if i² digits can be partitioned to sum to i via backtracking.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
For each i check if i² digits can be partitioned to sum to i via backtracking.
Related patterns: Math, Backtracking
2698.cs
C#
// Approach: For each i check if i² digits can be partitioned to sum to i via backtracking.
// Time: O(n * 2^d) Space: O(d)
public class Solution
{
public int PunishmentNumber(int n)
{
int ans = 0;
for (int i = 1; i <= n; i++)
{
int square = i * i;
if (isPossible(0, 0, square.ToString(), 0, i))
ans += square;
}
return ans;
}
// Returns true if the sum of any split of `numChars` equals to the target.
private bool isPossible(int accumulate, int running, string numChars, int s, int target)
{
if (s == numChars.Length)
return target == accumulate + running;
int d = numChars[s] - '0';
return isPossible(accumulate, running * 10 + d, numChars, s + 1, target) ||
isPossible(accumulate + running, d, numChars, s + 1, target);
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 22. Generate Parentheses(Medium)
- 29. Divide Two Integers(Medium)
- 37. Sudoku Solver(Hard)
- 40. Combination Sum II(Medium)