classSolution { public: intsubsetXORSum(vector<int>& nums){ int ans = 0; function<void(constint, constint)> backtracking = [&](constint i, constint current) -> void { if (i == nums.size()) { ans += current; return; } else { // use this backtracking(i + 1, current ^ nums[i]); // not use this backtracking(i + 1, current); } }; backtracking(0, 0); return ans; } };
时间复杂度: O(2^n),
空间复杂度: O(n).
1864. Minimum Number of Swaps to Make the Binary String Alternating
classSolution { public: intminSwaps(string s){ int ans = s.size(); vector<int> cnt(2, 0); for (char c : s) { ++cnt[c - '0']; } if (abs(cnt[0] - cnt[1]) > 1) return-1; for (char first : "01"s) { int current = 0; if (cnt.at(first - '0') + 1 == cnt.at('1' - first)) continue; for (int i = 0; i < s.size(); i += 2) { if (s[i] != first) { ++current; } } ans = min(ans, current); } return ans; } };
classFindSumPairs { vector<int> nums1, nums2; unordered_map<int, unordered_set<int>> m; public: FindSumPairs(vector<int>& _nums1, vector<int>& _nums2): nums1(move(_nums1)), nums2(move(_nums2)) { for (int i = 0; i < nums2.size(); ++i) { m[nums2[i]].insert(i); } } voidadd(int index, int val){ // O(1) m[nums2[index]].erase(index); nums2[index] += val; m[nums2[index]].insert(index); } intcount(int tot){ // O(nums1.length) int ans = 0; for (int i : nums1) { auto it = m.find(tot - i); if (it != m.end()) { ans += it->second.size(); } } return ans; } };
/** * Your FindSumPairs object will be instantiated and called as such: * FindSumPairs* obj = new FindSumPairs(nums1, nums2); * obj->add(index,val); * int param_2 = obj->count(tot); */
1866. Number of Ways to Rearrange Sticks With K Sticks Visible
本题我只想到了N^3的解法。
使用动态规划,状态转移方程为
1 2 3 4
ans = 0 for j inrange(k - 1, i): ans = (ans + dp(j, k - 1) * f2(i-1, j)) % MOD return ans
MOD = 10**9 + 7 @cache deff(i): if i <= 1: return1 else: return (i * f(i - 1)) % MOD @cache deff2(a, b): if a == b: return1 else: return (a * f2(a - 1, b)) % MOD @cache defdp(i: int, k: int) -> int: # [1:i], see k woods # print(i, k) if i < k: return0 elif i == k: return1 elif k == 1: # put i first and other after return f(i - 1) else: ans = 0 for j inrange(k - 1, i): # put i first and [j+1, i-1] after # pick num woods before # num = i - 1 - (j + 1) + 1 # C_i^num * num! # C(n,m)=n!/((n-m)!*m!)(m≤n) # print('add', dp(j, k - 1), (factorial(i) // factorial(i - num))) ans = (ans + dp(j, k - 1) * f2(i-1, j)) % MOD return ans classSolution: defrearrangeSticks(self, n: int, k: int) -> int: return dp(n, k)
classSolution: defrearrangeSticks(self, n: int, k: int) -> int: MOD = 10**9 + 7 @cache defdp(i: int, k: int) -> int: # [1:i], see k woods if i < k: return0 elif i == k: return1 elif k == 0: return0 else: # last wood can be seen, it must be `i`. dp(i-1, k - 1) # last wood can not be seen, (i - 1) * dp(i - 1, k) return (dp(i-1, k - 1) + (i - 1) * dp(i - 1, k)) % MOD