Given a string, your task is to calculate the number of different strings that can be created using its characters.
Example:
Input: s = "aabac"
Output: 20
Approach
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long qexp(long long a, long long b, long long m){long long res = 1;while (b){if (b % 2)res = res * a % m;a = a * a % m;b /= 2;}return res;}vector<long long> fact, invf;void precompute(int n){fact.assign(n + 1, 1);for (int i = 1; i <= n; i++)fact[i] = fact[i - 1] * i % MOD;invf.assign(n + 1, 1);invf[n] = qexp(fact[n], MOD - 2, MOD);for (int i = n - 1; i > 0; i--)invf[i] = invf[i + 1] * (i + 1) % MOD;}long long nCk(int n, int k){if (k < 0 || k > n)return 0;return fact[n] * invf[k] % MOD * invf[n - k] % MOD;}long long creatingStringII(string s){int n = s.size();map<char, int> mp;for (char c : s)mp[c]++;long long ans = fact[n];for (auto it = mp.begin(); it != mp.end(); it++)ans = ans * invf[it->second] % MOD;return ans;}int main(){string s = "aabac";precompute(1e6);cout << creatingStringII(s) << "\n";return 0;}
No comments:
Post a Comment