Advertisement
pb_jiang

LC1621 WA

Jan 14th, 2023
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. class Solution
  2. {
  3.     const int mod = 1e9 + 7;
  4.     vector<vector<array<int, 2>>> dp;
  5.     int search(int n, int k, int end)
  6.     {
  7.         if (n == k + 1)
  8.             return end == 1;
  9.         if (k == 0)
  10.             return end == 0;
  11.         if (n < 0)
  12.             return 0;
  13.         if (dp[n][k][end] != -1)
  14.             return dp[n][k][end];
  15.  
  16.         int ret = 0;
  17.         // end 1: the end is occupied
  18.         // end 0: the end is not occupied
  19.         switch (end) {
  20.             case 0:
  21.                 ret = (ret + search(n - 1, k, 0)) % mod; // not take i
  22.                 ret = (ret + search(n - 1, k, 1)) % mod; // not take i
  23.                 break;
  24.             case 1:
  25.                 ret = (ret + search(n - 1, k - 1, 0)) % mod; // take i, and make it a single group
  26.                 ret = (ret + search(n - 1, k - 1, 1)) % mod; // take i, and make it a single group
  27.                 ret = (ret + search(n - 1, k, 1)) % mod;     // take i, and make it a suffix to previous group
  28.                 break;
  29.         }
  30.         return dp[n][k][end] = ret;
  31.     }
  32.  
  33.   public:
  34.     int numberOfSets(int n, int k)
  35.     {
  36.         dp = vector<vector<array<int, 2>>>(n + 1, vector<array<int, 2>>(k + 1, array<int, 2>{-1, -1}));
  37.         return (search(n - 1, k, 0) + search(n - 1, k, 1)) % mod;
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement