Skip to content

Commit

Permalink
Add LeetCode January 03.
Browse files Browse the repository at this point in the history
  • Loading branch information
pin3da committed Jan 3, 2021
1 parent ddcf7fa commit c7dbb48
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions solved/LeetCode/Challenges/2020/January/03.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include<bits/stdc++.h>

using namespace std;

bool IsDiv(int a, int b) {
if (b == 0) {
return false;
}
return (a % b) == 0;
}

class Solution {
using Mask = bitset<15>;
int n;
vector<int> seen;
int dp(Mask mask) {
if (mask.count() == n) {
return 1;
}
if (seen[mask.to_ulong()] != -1) {
return seen[mask.to_ulong()];
}
int ans = 0;
int pos = mask.count() + 1;
for (int i = 0; i < n; i++) {
int val = i + 1;
if (mask[i] == 0 && (IsDiv(val, pos) || IsDiv(pos, val))) {
Mask next = mask;
next.set(i);
ans += dp(next);
}
}
seen[mask.to_ulong()] = ans;
return ans;
}

public:
int countArrangement(int n) {
seen.assign((1 << 15) + 10, -1);
this->n = n;
return dp(Mask());
}
};

0 comments on commit c7dbb48

Please sign in to comment.