classSolution: defstringMatching(self, words: List[str]) -> List[str]: ans = set() n = len(words) for i inrange(n): for j inrange(i + 1, n): if words[i].find(words[j]) != -1: ans.add(words[j]) if words[j].find(words[i]) != -1: ans.add(words[i]) return [i for i in ans]
1409. Queries on a Permutation With Key
用List模拟Permutation的变化。
寻找位置时使用顺序查找。
时间复杂度: O(m + queries.length * m),
空间复杂度: O(m + queries.length).
classSolution { public: vector<int> processQueries(vector<int>& queries, int m){ list<int> P; for (int i = 1; i <= m; ++i) { P.push_back(i); } vector<int> ans(queries.size()); for (int i = 0; i < queries.size(); ++i) { auto it = P.begin(); int position = 0; while (it != P.end() && *it != queries[i]) { ++it; ++position; } ans[i] = position; P.push_front(*it); P.erase(it); } return ans; } };
Discuss中提供了一种Fenwick Tree的解法,时间复杂度: O(queries.length * log m + m * log m).
classSolution: defnumOfWays(self, n: int) -> int: import functools @functools.lru_cache(None) defunzip(x: int) -> List[int]: a = x // (3*3) b = (x // (3)) % 3 c = x % 3 return [a, b, c] @functools.lru_cache(None) defrow_not_valid(state: int) -> bool: a, b, c = unzip(state) return a == b or b == c @functools.lru_cache(None) defbetween_row_valid(a: int, b: int) -> bool: al = unzip(a) bl = unzip(b) returnall(al[i] != bl[i] for i inrange(3)) @functools.lru_cache(None) defdp(n: int, state: int) -> int: if row_not_valid(state): return0 else: if n == 0: return1 else: ans = 0 for i inrange(3**3): ifnot row_not_valid(i) and between_row_valid(state, i): ans += dp(n-1, i) return ans ans = 0 for i inrange(3**3): ifnot row_not_valid(i): ans += dp(n-1, i) return ans % (1000000000 + 7)