Skip to content

Commit 908d2d5

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 2060828 commit 908d2d5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
// Helper function to add two integers
4+
int add(int a, int b){
5+
return (a + b); // Returns the sum of a and b
6+
}
7+
8+
// Helper function to multiply two integers
9+
int multi(int a, int b){
10+
return (a * b); // Returns the product of a and b
11+
}
12+
13+
// Function to calculate the number of ways to paint the fence with n posts and k colors
14+
int solve(int n, int k){
15+
// Base case: If there is only one post, there are k ways to paint it with k colors
16+
if(n == 1) return k;
17+
18+
// Base case: If there are two posts, there are k * k ways to paint them
19+
// (each post can be painted with any of the k colors)
20+
if(n == 2) return add(k, multi(k, k-1));
21+
22+
// Recurrence relation:
23+
// The number of ways to paint n posts is calculated as:
24+
// dp[n] = (dp[n-1] * (k-1)) + (dp[n-2] * (k-1))
25+
// This is based on the fact that we can paint the nth post in (k-1) ways to avoid
26+
// repeating the color of the (n-1)th post.
27+
int ans = add(multi(solve(n-2, k), k-1), multi(solve(n-1, k), k-1));
28+
29+
// Return the calculated number of ways to paint n posts
30+
return ans;
31+
}
32+
33+
// Main function to initiate the calculation and return the result
34+
int countWays(int n, int k) {
35+
return solve(n, k); // Call the solve function to calculate the result
36+
}
37+
};

0 commit comments

Comments
 (0)