Leetcode Problem 2048. Next Greater Numerically Balanced Number
2048. Next Greater Numerically Balanced Number
Leetcode Solutions
Backtracking to Generate Numerically Balanced Numbers
Define a backtracking function that takes the current position, the target length of the number, the current number being constructed, and a counter for the digits.
If the current position equals the target length, check if the current number is numerically balanced and yield it as a result.
Iterate over possible digits from 1 to the target length.
Prune the search if the count of the current digit is already equal to the digit (since adding more would violate the balance).
Prune the search if there aren't enough places left to satisfy the digit's required count.
Otherwise, increment the count for the digit, add it to the current number, and recurse to the next position.
After the recursive call, backtrack by decrementing the count of the digit.
Iterate over the possible lengths of the numerically balanced number, starting from the length of n and possibly one more digit.
For each generated number, if it is greater than n, return it as the answer.
Brute Force Search for Numerically Balanced Numbers