|
| 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: When there is only 1 post, there are k ways to paint it with k colors |
| 16 | + if(n == 1) return k; |
| 17 | + |
| 18 | + // Base case: When there are 2 posts, there are k * k ways to paint them |
| 19 | + // 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 |
| 20 | + if(n == 2) return add(k, multi(k, k-1)); |
| 21 | + |
| 22 | + // Initializing the values for the first two posts (dp[1] and dp[2]) |
| 23 | + // prev2 represents dp[i-2] (previous to the current value) |
| 24 | + // prev1 represents dp[i-1] (the previous value) |
| 25 | + int prev2 = k; // Ways to paint the first post |
| 26 | + int prev1 = add(k, multi(k, k-1)); // Ways to paint two posts |
| 27 | + |
| 28 | + // Iteratively calculate the number of ways to paint posts from 3 to n |
| 29 | + for(int i = 3; i <= n; i++){ |
| 30 | + // Calculate the number of ways to paint the i-th post: |
| 31 | + // - The first part (multi(prev2, 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 (multi(prev1, k-1)) represents the case where the i-th post is painted with a different color than the (i-1)-th post |
| 33 | + int current = add(multi(prev2, k-1), multi(prev1, k-1)); |
| 34 | + |
| 35 | + // Move the values forward for the next iteration |
| 36 | + prev2 = prev1; // Update prev2 to the value of prev1 |
| 37 | + prev1 = current; // Update prev1 to the new current value |
| 38 | + } |
| 39 | + |
| 40 | + // Return the result for the nth post, which is stored in prev1 |
| 41 | + return prev1; |
| 42 | + } |
| 43 | + |
| 44 | + // Main function to compute the number of ways to paint the fence |
| 45 | + int countWays(int n, int k) { |
| 46 | + // Call the solve function to compute the result |
| 47 | + return solve(n, k); |
| 48 | + } |
| 49 | +}; |
0 commit comments