nikunjsoni

1866

May 17th, 2021
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     #define ll long long
  4.     ll mod = int(1e9)+7LL;
  5.     int rearrangeSticks(int n, int k) {
  6.         if(k > n) return 0;
  7.         if(n == k) return 1;
  8.        
  9.         // Create DP table.
  10.         ll dp[n+1][k+1];
  11.         memset(dp, 0, sizeof dp);
  12.        
  13.         // Initialize table.
  14.         for(int i=0; i<=k; i++)
  15.             dp[i][i] = 1;
  16.        
  17.         // Fill the table in bottom up fashion.
  18.         // 1. Place tallest stick at end and add dp(n-1, k-1) ways.
  19.         // 2. Place one of the smallest sticks at end and add (n-1)*dp(n-1,k) ways.
  20.         for(int i=1; i<=n; i++)
  21.             for(int j=1; j<=min(i,k); j++)
  22.                 dp[i][j] = (dp[i-1][j-1] + (dp[i-1][j]*(i-1))%mod)%mod;
  23.        
  24.         return dp[n][k];
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment