Description
You are given a string num. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of the digits at odd indices.
Return the number of distinct permutations of num that are balanced.
Since the answer may be very large, return it modulo 109 + 7.
A permutation is a rearrangement of all the characters of a string.
Β
Example 1:
Input: num = "123"
Output: 2
Explanation:
- The distinct permutations of
numare"123","132","213","231","312"and"321". - Among them,
"132"and"231"are balanced. Thus, the answer is 2.
Example 2:
Input: num = "112"
Output: 1
Explanation:
- The distinct permutations of
numare"112","121", and"211". - Only
"121"is balanced. Thus, the answer is 1.
Example 3:
Input: num = "12345"
Output: 0
Explanation:
- None of the permutations of
numare balanced, so the answer is 0.
Β
Constraints:
2 <= num.length <= 80numconsists of digits'0'to'9'only.
Solution
Python3
class Solution:
def countBalancedPermutations(self, num: str) -> int:
M = 10**9 + 7
tot = sum(map(int, num))
c = Counter(map(int, num))
@cache
def solve(d, es, os, s):
if es < 0 or os < 0: return 0
if d == 10: return s == tot-s
if c[d] == 0: return solve(d+1, es, os, s)
ans = 0
for ec in range(c[d]+1):
oc = c[d]-ec
ans += comb(es, ec) * comb(os, oc) * solve(d+1, es-ec, os-oc, s+(ec*d))
return ans % M
odd = len(num) // 2
return solve(0, len(num)-odd, odd, 0) % M