2020 LCP 力扣團隊賽
阿新 • • 發佈:2020-09-20
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();
}
};