|
| 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 | + // Recursive function with memoization to calculate the number of ways to paint the fence |
| 14 | + // n: number of posts, k: number of colors, dp: memoization array |
| 15 | + int solve(int n, int k, vector<int>& dp){ |
| 16 | + // Base case 1: If there is only one post, there are k ways to paint it with k colors |
| 17 | + if(n == 1) return k; |
| 18 | + |
| 19 | + // Base case 2: If there are two posts, there are k * k ways to paint them |
| 20 | + if(n == 2) return add(k, multi(k, k-1)); |
| 21 | + |
| 22 | + // If the result for the current number of posts is already computed (cached), return it |
| 23 | + if(dp[n] != -1) return dp[n]; |
| 24 | + |
| 25 | + // Recursive case: Use the recurrence relation to calculate the number of ways to paint n posts |
| 26 | + // D(n) = (D(n-1) * (k-1)) + (D(n-2) * (k-1)) |
| 27 | + dp[n] = add(multi(solve(n-2, k, dp), k-1), multi(solve(n-1, k, dp), k-1)); |
| 28 | + |
| 29 | + // Return the result for the current number of posts |
| 30 | + return dp[n]; |
| 31 | + } |
| 32 | + |
| 33 | + // Main function to initialize the DP array and call the solve function |
| 34 | + int countWays(int n, int k) { |
| 35 | + // Create a memoization array to store the result for each number of posts (initially -1) |
| 36 | + vector<int> dp(n+1, -1); |
| 37 | + |
| 38 | + // Call the solve function to calculate and return the result |
| 39 | + return solve(n, k, dp); |
| 40 | + } |
| 41 | +}; |
0 commit comments