Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created April 11, 2020 12:51
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/b43f1269956e4663e9bf9a2b9c1c94ec to your computer and use it in GitHub Desktop.
Save adamkorg/b43f1269956e4663e9bf9a2b9c1c94ec to your computer and use it in GitHub Desktop.
Leetcode 276: Paint Fence (O(n^2) space)
#include <iostream>
#include <vector>
using namespace std;
int numWays(int n, int k) {
if (n==0 || k==0) return 0;
vector<vector<int>> dp(k, vector<int>(n,1));
for (int c=1; c<n; ++c) {
for (int r=0; r<k; ++r) {
int sumPrevCol = 0;
for (int i=0; i<k; ++i) sumPrevCol += dp[i][c-1];
dp[r][c] = sumPrevCol - (c<2 ? 0 : dp[r][c-2]);
}
}
int res = 0;
for (int r=0; r<k; ++r) res += dp[r][n-1];
return res;
}
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