Advertisement
Fastrail08

Tiling With Dominoes 2 * N

May 31st, 2025
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long long getWaysToTile(int n, vector<long long> &memo){
  5.     // there could be one more base case, n == 0, no way to tile it, which can be done in 1 way, don't tile it; if(n == 0) return 1;
  6.     // base case
  7.     if(n == 1 || n == 2){
  8.         return n;
  9.     }
  10.     if(memo[n] != -1){
  11.         return memo[n];
  12.     }
  13.     long long verticallyPlaced = 0, horizontallyPlaced = 0;
  14.     // 2 * 1
  15.     // multiplied by 1 as: number of ways to tile [2 * 1](if placed vertically) * number of ways to tile [2 * (N - 1)]
  16.     //ways to tile 2 * 1 = 1; place one tile vertically
  17.     verticallyPlaced = 1 * getWaysToTile(n - 1, memo);
  18.    
  19.     // 1 * 2
  20.     // multiplied by 1 as: number of ways to tile [2 * 1](if placed horizontally) * number of ways to tile [2 * (N - 2)]
  21.     //ways to tile 2 * 1 = 1; place 2 tiles horizontally, but there is only way to do it as the tiles are same
  22.     horizontallyPlaced = 1* getWaysToTile(n - 2, memo);
  23.    
  24.     return memo[n] = verticallyPlaced + horizontallyPlaced;
  25.    
  26. }
  27.  
  28. long long getWaysToTileDP(int n){
  29.     // 1. Storage & Meaning - dp[i] = number of ways to tile 2 * i board
  30.     vector<long long> dp(n + 1, - 1);
  31.    
  32.     //2. Direction - smallest problem at dp[0] = 1, dp[1] = 1, dp[2] = 2;
  33.     //             - largest problem at dp[n] = ways to tile 2 * N
  34.     // travel from smallest to largest problem
  35.     dp[0] = dp[1] = 1;
  36.     dp[2] = 2;
  37.    
  38.     //3. Travel & Solve
  39.     // Check tree, what subproblems do the state(n) calls to, replicate the same in the loop
  40.     for(int i = 3; i <= n; i++){
  41.         dp[i] = dp[i - 1] + dp[i - 2];
  42.     }
  43.     return dp[n];
  44. }
  45.  
  46. int main() {
  47.     // your code goes here
  48.     int n;
  49.     cin >> n;
  50.     vector<long long> memo(n + 1, -1);
  51.     cout << getWaysToTile(n, memo) << '\n';
  52.     cout << getWaysToTileDP(n) << '\n';
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement