Skip to content

Commit 3a88e7c

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent da79358 commit 3a88e7c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
// Function to calculate derangements using tabulation (iterative dynamic programming)
4+
int solve(int n) {
5+
// Create a DP array to store the number of derangements for each value from 0 to n
6+
vector<int> dp(n + 1, -1);
7+
8+
// Base cases:
9+
// For n = 1, there are no valid derangements
10+
dp[1] = 0;
11+
12+
// For n = 2, there is exactly one valid derangement
13+
dp[2] = 1;
14+
15+
// Fill the DP array iteratively using the relation:
16+
// D(i) = (i-1) * (D(i-1) + D(i-2))
17+
for (int i = 3; i <= n; i++) {
18+
dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]);
19+
}
20+
21+
// Return the result for n
22+
return dp[n];
23+
}
24+
25+
// Main function to calculate derangements
26+
int countDer(int n) {
27+
// Delegate the computation to the solve function
28+
return solve(n);
29+
}
30+
};

0 commit comments

Comments
 (0)