大佬看看这个代码没问题吧,第二题 DFS,加了个简单的剪枝 import sys def per(origin, target): for i in target: if i not in origin: return [] res = [] dfs(origin, target, [], "", res) return res def dfs(old, target, path, now, res): if not old: # 遍历结束 # 判断是否相等 if now == target: res.append(path.copy()) return if not is_in(now, target): # 未遍历结束 # 判断是否已经不相等 return cur = old[0] if cur not in target: path.append("d") dfs(old[1:], target, path, now, res) path.pop() else: path.append("d") dfs(old[1:], target, path, now, res) path.pop() path.append("l") dfs(old[1:], target, path, cur + now, res) path.pop() path.append("r") dfs(old[1:], target, path, now + cur, res) path.pop() def is_in(ls1, ls2): # 判断 ls1 是否为 ls2 的连续子集 str1 = "".join(map(str, ls1)) str2 = "".join(map(str, ls2)) return str1 in str2 if __name__ == "__main__": s = int(sys.stdin.readline().strip()) ans = "" for _ in range(s): origin = sys.stdin.readline().strip() target = sys.stdin.readline().strip() ans += "{\n" res = per(origin, target) res.sort() # print(res) if res: for each_res in res: ans += " ".join(each_res) + " \n" ans += "}\n" if ans: ans = ans[:-1] print(ans)
点赞 评论

相关推荐

勇敢的联想人前程似锦:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
牛客网
牛客企业服务