Created
April 11, 2020 12:53
-
-
Save adamkorg/92d8901821d59a900241c9e1b63e0ff4 to your computer and use it in GitHub Desktop.
Leetcode 276: Paint Fence (O(1) space)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
int numWays(int n, int k) { | |
if (n==0 || k==0) return 0; | |
if (n==1) return k; | |
if (n==2) return k*k; | |
vector<int> dp {0,1,k}; | |
for (int c=2; c<n; ++c) { | |
dp[0]=dp[1]; dp[1]=dp[2]; | |
dp[2] = (dp[1]*k) - dp[0]; | |
} | |
return dp[2]*k; | |
} | |
int main() { | |
cout << numWays(3, 2) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment