【发布时间】:2022-01-07 05:24:20
【问题描述】:
例如,让我们考虑一个任务,我们需要找到给定字符串的所有排列,保留字符序列但改变大小写。
这里是没有.pop()的回溯解决方案:
def letterCasePermutation(S):
"""
:type S: str
:rtype: List[str]
"""
def backtrack(sub="", i=0):
if len(sub) == len(S):
res.append(sub)
else:
if S[i].isalpha():
backtrack(sub + S[i].swapcase(), i + 1)
backtrack(sub + S[i], i + 1)
res = []
backtrack()
return res
这是.pop()的解决方案:
def letterCasePermutation(s):
def backtrack(idx, path):
if idx == n:
res.append("".join(path))
return
ele = s[idx]
if ele.isnumeric():
path.append(ele)
backtrack(idx + 1, path)
path.pop()
else:
path.append(ele.lower())
backtrack(idx + 1, path)
path.pop()
path.append(ele.upper())
backtrack(idx + 1, path)
path.pop()
n = len(s)
res = []
backtrack(0, [])
return res
两个代码示例都是回溯,还是我应该调用第一个 DFS 而第二个回溯?
【问题讨论】:
-
考虑将元素
x添加到列表s的两种方法。 1)s + [x]返回一个新列表,不修改s。 2)s.append(x)修改s。如果以后要重用s,情况(1)可以直接重用s,但情况(2)需要先从s弹出x。 -
第一个示例使用代码堆栈和递归上下文隐式推送和弹出在第二个示例中显式执行的操作到
path,如path.append(..)和path.pop()。
标签: algorithm depth-first-search backtracking recursive-backtracking