File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
24 - Dynamic Programming Problems/09 - Dis-arrangement of Balls Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Helper function to calculate derangements recursively with memoization
4+ int solve (int n, vector<int >& dp) {
5+ // Base case: For n = 1, no valid dearrangements exist
6+ if (n == 1 ) return 0 ;
7+
8+ // Base case: For n = 2, exactly one valid dearrangement exists
9+ if (n == 2 ) return 1 ;
10+
11+ // If the result for this value of n has already been computed, return it
12+ if (dp[n] != -1 ) return dp[n];
13+
14+ // Use the recursive relation:
15+ // D(n) = (n-1) * (D(n-1) + D(n-2))
16+ dp[n] = (n-1 ) * (solve (n-1 , dp) + solve (n-2 , dp));
17+
18+ // Return the computed result
19+ return dp[n];
20+ }
21+
22+ // Main function to compute derangements of n items
23+ int countDer (int n) {
24+ // Create a memoization array initialized with -1
25+ // dp[i] will store the number of derangements for i items
26+ vector<int > dp (n+1 , -1 );
27+
28+ // Call the helper function to compute the result
29+ return solve (n, dp);
30+ }
31+ };
You can’t perform that action at this time.
0 commit comments