2020 LCP 力扣团队赛
1. 黑白方格画
二进制枚举
class Solution {
public:
int paintingPlan(int n, int k) {
map<int,int>ans;
if(k == n*n)return 1;
for(int i = 0;i < (1<<n);i++){
for(int j = 0;j < (1<<n);j++){
int x = __builtin_popcount(i);
int y = __builtin_popcount(j);
ans[(x+y)*n-x*y]++;
}
}
return ans[k];
}
};
2. 魔术排列
纯模拟
class Solution:
def isMagic(self, target: List[int]) -> bool:
n = len(target)
x = [i+1 for i in range(n)]
idx = 0
cnt = 0
k = -1
while idx < n:
x = x[cnt:][1::2] + x[cnt:][::2]
cnt = 0
if x[cnt] != target[idx]:
return False
c = 0
while idx < n and x[cnt] == target[idx]:
cnt += 1
idx += 1
c += 1
if k == -1:
k = c
else:
if c != k:
if idx == n:
return True
return False
return True
3. 数字游戏
两个堆维护中位数
class Solution {
public:
const int mod = 1e9+7;
vector<int> numsGame(vector<int>& nums) {
priority_queue<int,vector<int>,greater<int>>y;
priority_queue<int,vector<int>,less<int>>x;
for(int i = 0;i < nums.size();i++){
nums[i] -= i;
}
vector<int>ans;
long long sum1 = 0,sum2 = 0;
for(int i : nums){
if(x.empty())x.push(i),sum1+=i;
else{
int tp = x.top();
if(i <= tp){
x.push(i);
sum1 += i;
}
else{
y.push(i);
sum2 += i;
}
while(x.size() > y.size() + 1){
y.push(x.top());sum2 += x.top();
sum1 -= x.top();x.pop();
}
if(x.size() == y.size()-1){
x.push(y.top());sum1 += y.top();
sum2 -= y.top();y.pop();
}
}
long long mid = x.top();
//cout << (sum2-y.size()*mid) + (x.size()*mid - sum1) % mod << endl;
ans.push_back(((sum2-y.size()*mid) + (x.size()*mid - sum1)) % mod);
}
return ans;
}
};
4. 古董键盘
别人的一份代码
class Solution {
private:
/* 计算组合数 */
int C(int m, int n) {
if ((n == 0) || (n == m))
return 1;
int ret = 1;
for (int i = 1; i <= n; ++i) {
ret *= (m - i + 1);
ret /= i;
}
return ret;
}
public:
int keyboard(int k, int n) {
vector<long long> dp(n + 1, 0);
/* 按键0次则得出唯一的一种内容: 空 */
dp[0] = 1;
/* 遍历26个字母(26种货物) */
for (int i = 0; i < 26; ++i) {
/* 遍历背包的容量(从大到小) */
for (int j = n; j >= 1; --j) {
/* 放入x个当前字母 */
for (int x = 1; x <= k; ++x) {
if (x > j)
continue;
dp[j] += C(j, x) * dp[j - x];
dp[j] %= 1000000007;
}
}
}
return dp.back();
}
};