classSolution { constint mod = 1e9 + 7; int f; map<pair<int, int>, int> memo; // [begin, end), the index of insert bar intbacktracking(int begin, int end, int bar){ if (memo.find({begin, bar}) != memo.end()) { return memo[{begin, bar}]; } if (bar == 0) { if (end - begin + 1 <= f) return1; else return0; } int ans = 0; for (int i = begin; i < end && i - begin + 1 <= f; ++i) { // insert in i ans += backtracking(i + 1, end, bar - 1); ans %= mod; } memo[{begin, bar}] = ans; return ans; } public: intnumRollsToTarget(int d, int f, int target){ this->f = f; int ans = backtracking(0, target - 1, d - 1); return ans; } };
1156. Swap For Longest Repeated Character Substring
One pass, 更新可以获得的最长长度。
需要观察到: 最长长度的获得和中间空的字母无关,而只和前后有无需要的字母有关。
classMajorityChecker { unordered_map<int, vector<int>> appear_index; vector<int> arr; public: MajorityChecker(vector<int>& arr) { for (int i = 0; i < arr.size(); ++i) { appear_index[arr[i]].push_back(i); } this->arr = arr; } intquery(int left, int right, int threshold){ std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> dist6(left,right); // distribution in range [left, right] for (int i = 0; i < 20; ++i) { int a = arr[dist6(rng)]; constauto& index = appear_index[a]; auto l = lower_bound(index.cbegin(), index.cend(), left); auto r = upper_bound(index.cbegin(), index.cend(), right); if (r - l >= threshold) { return a; } } return-1; } };
/** * Your MajorityChecker object will be instantiated and called as such: * MajorityChecker* obj = new MajorityChecker(arr); * int param_1 = obj->query(left,right,threshold); */