Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Problem Statement: https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/
- */
- class Solution {
- public:
- double getProbability(vector<int>& balls) {
- int k, n;
- double valid, total;
- k = balls.size();
- n = accumulate(balls.begin(), balls.end(), 0) / 2;
- valid = total = 0;
- vector<int> b(k);
- // helper functions
- auto fact = [&](int n) {
- double f = 1;
- while (n)
- f *= n--;
- return f;
- };
- auto state = [&]() {
- int box_1, box_2;
- double f1, f2;
- if (accumulate(b.begin(), b.end(), 0) != n)
- return;
- box_1 = box_2 = 0;
- f1 = f2 = fact(n);
- for (int i = 0; i < k; i++) {
- box_1 += b[i] > 0;
- box_2 += balls[i] - b[i] > 0;
- if (b[i]) {
- box_1++;
- f1 /= fact(b[i]);
- }
- if (balls[i] - b[i]) {
- box_2++;
- f2 /= fact(balls[i] - b[i]);
- }
- }
- valid += (box_1 == box_2) * f1 * f2;
- total += f1 * f2;
- };
- function<void(int)> recurse = [&](int pos) {
- if (pos == k) {
- state();
- return;
- }
- for (int i = 0; i <= balls[pos]; i++) {
- b[pos] = i;
- recurse(pos + 1);
- }
- };
- recurse(0);
- return valid / total;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement