Skip to content

Commit ac4ebfe

Browse files
authored
Create 01 - Recursive Approach.cpp
1 parent 61b3db0 commit ac4ebfe

File tree

1 file changed

+22
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)