1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { int MOD = (int) 1e9 + 7; public int countKSubsequencesWithMaxBeauty(String s, int k) { int n = s.length(); int[] cnt = new int[26]; for (int i = 0; i < n; ++i) cnt[s.charAt(i) - 'a']++; var cc = new TreeMap<Integer, Integer>(); for (int c : cnt) if (c > 0) cc.put(c, cc.getOrDefault(c, 0) + 1);
long res = 1; for (Map.Entry<Integer, Integer> entry : cc.descendingMap().entrySet()) { int num = entry.getKey(), count = entry.getValue(); if (count >= k) return (int) ((res * comb(count, k) % MOD ) % MOD * pow(num, k) % MOD); res = res * pow(num, count) % MOD; k -= count; } return 0; }
private long pow(long x, int n) { long res = 1; for (; n > 0; n /= 2) { if (n % 2 > 0) res = res * x % MOD; x = x * x % MOD; } return res; }
private long comb(long n, int k) { long res = n; for (int i = 2; i <= k; i++) res = res * --n / i; return res % MOD; } }
|