Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created April 11, 2020 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/92d8901821d59a900241c9e1b63e0ff4 to your computer and use it in GitHub Desktop.
Save adamkorg/92d8901821d59a900241c9e1b63e0ff4 to your computer and use it in GitHub Desktop.
Leetcode 276: Paint Fence (O(1) space)
#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