|
| 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 | + // Initialize a dynamic programming (DP) array to store the number of ways to paint i posts |
| 16 | + // dp[i] will store the number of ways to paint i posts |
| 17 | + vector<int> dp(n+1, -1); |
| 18 | + |
| 19 | + // Base case: For 1 post, there are k ways to paint it using k colors |
| 20 | + dp[1] = k; |
| 21 | + |
| 22 | + // Base case: For 2 posts, there are k * k ways to paint them |
| 23 | + // The first post can be painted with any of the k colors, and the second post can be painted with any of the k colors |
| 24 | + dp[2] = add(k, multi(k, k-1)); |
| 25 | + |
| 26 | + // Fill the DP array iteratively for posts from 3 to n |
| 27 | + // Use the recurrence relation: |
| 28 | + // dp[i] = (dp[i-1] * (k-1)) + (dp[i-2] * (k-1)) |
| 29 | + for(int i = 3; i <= n; i++){ |
| 30 | + // Calculate the number of ways to paint i posts: |
| 31 | + // - The first part (dp[i-1] * (k-1)) represents the case where the i-th post is painted with a different color than the (i-1)-th post |
| 32 | + // - The second part (dp[i-2] * (k-1)) represents the case where the i-th post is painted with a different color than the (i-1)-th post |
| 33 | + dp[i] = add(multi(dp[i-2], k-1), multi(dp[i-1], k-1)); |
| 34 | + } |
| 35 | + |
| 36 | + // Return the result for the nth post |
| 37 | + return dp[n]; |
| 38 | + } |
| 39 | + |
| 40 | + // Main function to compute the number of ways to paint the fence |
| 41 | + int countWays(int n, int k) { |
| 42 | + // Call the solve function to compute the result |
| 43 | + return solve(n, k); |
| 44 | + } |
| 45 | +}; |
0 commit comments