File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed
24 - Dynamic Programming Problems/09 - Dis-arrangement of Balls Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the number of derangements for n items
4+ int countDer (int n) {
5+ // Base case: For n = 1, there is no valid dearrangement
6+ if (n == 1 ) return 0 ;
7+
8+ // Base case: For n = 2, there is exactly one valid dearrangement: {2, 1}
9+ if (n == 2 ) return 1 ;
10+
11+ // Recursive relation for derangement:
12+ // totalRelations = (n-1) * (countDer(n-1) + countDer(n-2))
13+ // Explanation:
14+ // - (n-1): Choose a position for the first item (other than its original position).
15+ // - countDer(n-1): Solve the subproblem for the remaining (n-1) items.
16+ // - countDer(n-2): Solve the subproblem for (n-2) items when swapping is involved.
17+ int totalRelations = (n-1 ) * (countDer (n-1 ) + countDer (n-2 ));
18+
19+ // Return the total number of derangements for n items
20+ return totalRelations;
21+ }
22+ };
You can’t perform that action at this time.
0 commit comments