713146. Count Lucky Permutations
Count Lucky Permutations
Summary
Given a string s containing only digits, we need to count the number of lucky permutations. A permutation is considered "lucky" if the sum of its digits is equal to the length of the permutation. For example, for the string "123", there are 3! (6) permutations: "123", "132", "213", "231", "312", and "321". Out of these, only two permutations ("123" and "132") have a digit sum equal to their length (i.e., 1 + 2 + 3 = 6), so the count is 2. This problem involves dynamic programming concepts.
Detailed Explanation
The approach here is to use dynamic programming to solve this problem. We'll create a 2D array dp where dp[i][j] represents the number of lucky permutations for the first i digits, ending with digit j.
Here's the step-by-step breakdown:
- Initialize the
dparray:dp[0][0] = 1, because there is only one way to get a lucky permutation for an empty string (which has length 0). - Fill up the first row of
dp:dp[i][j] = 0for alli > 0andj. This is because we can't have a lucky permutation starting with digitjif there are less thanj+1digits. - For each pair
(i, j)wherei > 0, calculate the number of lucky permutations ending withj:- If
j == 0, then the sum of the last digit is equal to the length (i.e., 1), so we add the value indp[i-1][0]to the result. - Otherwise, for each possible next digit
k, check if the sum of its digits is equal to the new length (i+1). If yes, then add the value indp[i-1][k]to the result.
- If
- Finally, return the sum of all values in the last row of
dp.
Time complexity: O(n), where n is the number of digits in the input string. This is because we only iterate over each digit once.
Space complexity: O(n), as we need to store the dp array.
Optimized Solutions
Java
public int countLuckyPermutations(String s) {
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 10; j++) {
if (i > 0 || j == 0) {
int sum = 0;
for (int k = 0; k < i; k++) {
sum += s.charAt(k) - '0';
}
sum += j;
if (sum == i) {
dp[i] += dp[i - 1];
}
}
}
}
return dp[n];
}