Skip to content

Commit da79358

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent ac4ebfe commit da79358

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
};

0 commit comments

Comments
 (0)