We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2842. Count K-Subsequences of a String With Maximum Beauty
组合数学
难点在于:
逻辑要清晰。
import java.math.BigInteger; class Solution { public int countKSubsequencesWithMaxBeauty(String s, int k) { final int MOD = (int) 1e9 + 7; int[] cnt = new int[26]; for (char c : s.toCharArray()) { cnt[c - 'a']++; } TreeMap<Integer, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder()); int cc = 0; for (int i = 0; i < 26; i++) { if (cnt[i] > 0) { treeMap.merge(cnt[i], 1, Integer::sum); cc++; } } if (cc < k) { return 0; } BigInteger ans = BigInteger.ONE; for (int key : treeMap.keySet()) { int val = treeMap.get(key); if (val <= k) { BigInteger tmp = BigInteger.valueOf(key); tmp = tmp.modPow(BigInteger.valueOf(val), BigInteger.valueOf(MOD)); ans = ans.multiply(tmp).mod(BigInteger.valueOf(MOD)); } else { ans = ans.multiply(BigInteger.valueOf(combo(val, k))); BigInteger tmp = BigInteger.valueOf(key); tmp = tmp.modPow(BigInteger.valueOf(k), BigInteger.valueOf(MOD)); ans = ans.multiply(tmp).mod(BigInteger.valueOf(MOD)); } k -= val; if (k <= 0) { break; } } return ans.intValue(); } // get m from n randomly private int combo(int n, int m) { if (m > n) { return 0; } BigInteger res = BigInteger.ONE; for (int i = 0; i < m; i++) { res = res.multiply(BigInteger.valueOf(n - i)); } for (int i = 1; i <= m; i++) { res = res.divide(BigInteger.valueOf(i)); } return res.intValue(); } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
2842. Count K-Subsequences of a String With Maximum Beauty
2842. Count K-Subsequences of a String With Maximum Beauty
组合数学
难点在于:
逻辑要清晰。
The text was updated successfully, but these errors were encountered: