Advertisement
MohammedShoaib

Probability of a Two Boxes Having The Same Number of Distinc

Jun 2nd, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. /*
  2. Problem Statement: https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/
  3. */
  4.  
  5. class Solution {
  6. public:
  7.     double getProbability(vector<int>& balls) {
  8.         int k, n;
  9.         double valid, total;
  10.         k = balls.size();
  11.         n = accumulate(balls.begin(), balls.end(), 0);
  12.         valid = total = 0;
  13.         vector<int> b(k);
  14.         double nCr[n + 1][n + 1];
  15.  
  16.         // initialize nCr
  17.         for (int i = 0; i < n; i++)
  18.             nCr[i][0] = 1;
  19.         for (int i = 1; i < n; i++)
  20.             nCr[0][i] = 0;
  21.         for (int i = 1; i < n; i++)
  22.             for (int j = 1; j < n; j++)
  23.                 nCr[i][j] = nCr[i - 1][j - 1] + nCr[i - 1][j];
  24.        
  25.         // helper function
  26.         auto state = [&]() {
  27.             if (accumulate(b.begin(), b.end(), 0) != n / 2)
  28.                     return;
  29.             double ways = 1;
  30.             int box_1, box_2;
  31.             box_1 = box_2 = 0;
  32.  
  33.             for (int i = 0; i < k; i++) {
  34.                 box_1 += b[i] > 0;
  35.                 box_2 += balls[i] - b[i] > 0;
  36.                 ways *= nCr[balls[i]][b[i]];
  37.             }
  38.  
  39.             valid += (box_1 == box_2) * ways;
  40.             total += ways;
  41.         };
  42.         function<void(int)> recurse = [&](int pos) {
  43.             if (pos == k) {
  44.                 state();
  45.                 return;
  46.             }
  47.             for (int i = 0; i <= balls[pos]; i++) {
  48.                 b[pos] = i;
  49.                 recurse(pos + 1);
  50.             }
  51.         };
  52.         recurse(0);
  53.  
  54.         return valid / total;
  55.     }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement