File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
24 - Dynamic Programming Problems/09 - Dis-arrangement of Balls Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate derangements using space-optimized approach
4+ int solve (int n) {
5+ // Base case: For n = 1, there are no valid derangements
6+ if (n == 1 ) return 0 ;
7+
8+ // Base case: For n = 2, there is exactly one valid derangement
9+ if (n == 2 ) return 1 ;
10+
11+ // Initialize variables to store results for the last two states
12+ // prev: D(n-2), curr: D(n-1)
13+ int prev = 0 ; // D(1)
14+ int curr = 1 ; // D(2)
15+
16+ // Loop to calculate D(n) iteratively using the relation:
17+ // D(i) = (i-1) * (D(i-1) + D(i-2))
18+ for (int i = 3 ; i <= n; i++) {
19+ // Compute the next derangement value
20+ int next = (i - 1 ) * (curr + prev);
21+
22+ // Update prev and curr for the next iteration
23+ prev = curr;
24+ curr = next;
25+ }
26+
27+ // Return the result for D(n)
28+ return curr;
29+ }
30+
31+ // Main function to calculate derangements
32+ int countDer (int n) {
33+ // Delegate the computation to the solve function
34+ return solve (n);
35+ }
36+ };
You can’t perform that action at this time.
0 commit comments