classSolution { public: /** * @param words: a set of stirngs * @param target: a target string * @param k: An integer * @return: output all the strings that meet the requirements */
intminDistance(string word1, string word2, int k){ int m = word1.size(); int n = word2.size(); if (m - n > k || n - m > k) return k + 1; vector<vector<int>> dp(m + 1, vector<int>(n + 1)); for (int i = 0; i <= m; i++) { dp[i][0] = i; } for (int j = 0; j <= n; j++) { dp[0][j] = j; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1[i - 1] == word2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else { dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])); } } } return dp[m][n]; }
vector<string> kDistance(vector<string> &words, string &target, int k){ // write your code here vector<string> res; for (auto &word: words) { if (minDistance(word, target, k) <= k) { res.push_back(word); } } return res; } };
2. 折纸
描述
折纸,每次都是将纸从右向左对折,凹痕为 0,凸痕为 1,求折 n 次后,将纸展开所得折痕组成的 01 序列。
classSolution: """ @param n: The folding times @return: the 01 string """
defgetString(self, n): # Write your code here defprintProcess(i, N, down): if i > N: return printProcess(i + 1, N, True) if down isTrue: res.append('0') else: res.append('1') printProcess(i + 1, N, False)
res = [] printProcess(1, n, True) return"".join(res)
classSolution: """ @param str: A string @return: all permutations """
defstringPermutation(self, s): # write your code here li = list(s) li.sort() q, nq = [""], [] for char in li: for ans in q: for i in range(len(ans), -1, -1): if i < len(ans) and char == ans[i]: break nq.append(ans[:i] + char + ans[i:]) q, nq = nq, [] q.sort() return q
classSolution: """ @param values: a vector of integers @return: a boolean which equals to true if the first player will win """
deffirstWillWin(self, values): # write your code here n = len(values) dp = [[[0, 0] for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i][0] = values[i] for gap in range(1, n): for i in range(n - gap): j = i + gap left = dp[i + 1][j][1] + values[i] right = dp[i][j - 1][1] + values[j] if left > right: dp[i][j][0] = left dp[i][j][1] = dp[i + 1][j][0] else: dp[i][j][0] = right dp[i][j][1] = dp[i][j - 1][0] return dp[0][n - 1][0] > dp[0][n - 1][1]