LeetCode 2478: Number of Beautiful Partitions

Problem Description

Explanation:

To solve this problem, we can iterate through all possible partitions of the string s and check if each partition satisfies the conditions of being beautiful. We can use dynamic programming to keep track of the number of beautiful partitions ending at each index of the string.

  1. Initialize a 2D DP array where dp[i][j] represents the number of beautiful partitions ending at index i with j substrings.
  2. Iterate through each index i of the string s and each possible number of substrings j.
  3. For each index i, calculate the number of beautiful partitions ending at index i with j substrings based on the previous results.
  4. Update the DP array accordingly.
  5. Finally, return the sum of all beautiful partitions with k substrings and a total length of at least minLength. :

Solutions

class Solution {
    public int countBeautifulString(String s, int k, int minLength) {
        int mod = 1000000007;
        int n = s.length();
        int[][] dp = new int[n + 1][k + 1];
        
        dp[0][0] = 1;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= k; j++) {
                int primeCount = 0;
                for (int l = i; l > 0 && i - l + 1 >= minLength; l--) {
                    if (s.charAt(l - 1) == '2' || s.charAt(l - 1) == '3' || s.charAt(l - 1) == '5' || s.charAt(l - 1) == '7') {
                        primeCount++;
                    }
                    if (primeCount > 0) {
                        dp[i][j] = (dp[i][j] + dp[l - 1][j - 1]) % mod;
                    }
                }
            }
        }
        
        int result = 0;
        for (int i = 0; i <= n; i++) {
            result = (result + dp[i][k]) % mod;
        }
        
        return result;
    }
}

Loading editor...