大佬看看这个代码没问题吧,第二题 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)
点赞 评论

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-04 14:35
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务