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);
- valid = total = 0;
- vector<int> b(k);
- double nCr[n + 1][n + 1];
- // initialize nCr
- for (int i = 0; i < n; i++)
- nCr[i][0] = 1;
- for (int i = 1; i < n; i++)
- nCr[0][i] = 0;
- for (int i = 1; i < n; i++)
- for (int j = 1; j < n; j++)
- nCr[i][j] = nCr[i - 1][j - 1] + nCr[i - 1][j];
- // helper function
- auto state = [&]() {
- if (accumulate(b.begin(), b.end(), 0) != n / 2)
- return;
- double ways = 1;
- int box_1, box_2;
- box_1 = box_2 = 0;
- for (int i = 0; i < k; i++) {
- box_1 += b[i] > 0;
- box_2 += balls[i] - b[i] > 0;
- ways *= nCr[balls[i]][b[i]];
- }
- valid += (box_1 == box_2) * ways;
- total += ways;
- };
- 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