classSolution { public: intmaxPower(string s){ constint n = s.size(); int l = 0, r = 0; int ans = 1; for (; r < s.size(); ++r) { if (s[r] == s[l]) continue; else { ans = max(ans, r - l); l = r; } } ans = max(ans, n - l); return ans; } };
1447. Simplified Fractions
枚举所有的分母和分子,并判断是否是最简形式。幸运的是,C++17已经内置提供gcd函数。
时间复杂度: O(n^2),
空间复杂度: O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: vector<string> simplifiedFractions(int n){ vector<string> ans; for (int down = 2; down <= n; ++down) { for (int up = 1; up < down; ++up) { if (gcd(up, down) == 1) { ans.push_back(to_string(up) + "/" + to_string(down)); } } } return ans; } };
classSolution: deflargestNumber(self, cost: List[int], target: int) -> str: unique = {} seen = set() for i inrange(len(cost) - 1, -1, -1): if cost[i] notin seen: seen.add(cost[i]) unique[i + 1] = cost[i] @lru_cache(None) defdp(t: int) -> int: if t < 0: return -1 if t == 0: return0 ans = -1 for i in unique: tmp = dp(t - unique[i]) if tmp >= 0: ans = max(ans, tmp * 10 + i) return ans ans = dp(target) returnstr(ans) if ans >= 0else'0'