字符串交织递归求解时满足条件能否清空调用栈直接返回True?
问题解答
递归返回逻辑疑问解答
你提到的递归返回问题,答案是必须逐层向上返回,无法直接忽略剩余栈帧给最外层返回结果。Python的递归调用基于调用栈实现,每一层递归的返回值只会传递给调用它的上一层函数,没有跨栈帧直接终止所有递归的机制。不过你可以在每层拿到子递归返回的True后,立刻向上返回该值,不需要执行当前层剩余逻辑,除了多几次返回操作外,不会产生多余的计算开销,实际效果和直接终止所有递归一致。
现有代码问题说明
你的代码存在几处可修复的问题:
- 缺少指针越界判断:当
pointer_one已经遍历完one或者pointer_two遍历完two时,直接访问one[pointer_one]或者two[pointer_two]会触发索引越界报错 - 条件判断笔误:代码中
two[pointer_two] != two[pointer_two]是无效判断,你实际要写的应该是two[pointer_two] != three[pointer_three] - 递归结果未提前返回:递归探索拿到
True后没有直接终止当前层逻辑返回结果,后续的指针移动逻辑会覆盖正确结果 - 长度前置校验缺失:如果
len(one) + len(two) != len(three),可以直接返回False,不需要后续计算
修正后的实现代码
def interweavingStrings(one, two, three, pointer_one=0, pointer_two=0, pointer_three=0): # 前置校验,长度不匹配直接返回False if len(one) + len(two) != len(three): return False # 已经遍历完three,检查两个源字符串是否也刚好用完 if pointer_three == len(three): return pointer_one == len(one) and pointer_two == len(two) # one还有未遍历字符,且当前字符匹配,走one指针后移的路径 if pointer_one < len(one) and one[pointer_one] == three[pointer_three]: if interweavingStrings(one, two, three, pointer_one + 1, pointer_two, pointer_three + 1): return True # two还有未遍历字符,且当前字符匹配,走two指针后移的路径 if pointer_two < len(two) and two[pointer_two] == three[pointer_three]: if interweavingStrings(one, two, three, pointer_one, pointer_two + 1, pointer_three + 1): return True # 两个路径都走不通,返回False return False
优化建议
如果输入字符串较长,可以加上记忆化缓存,避免重复计算相同的(pointer_one, pointer_two)状态,时间复杂度可以从O(2^(m+n))降到O(m*n),其中m、n分别是one和two的长度。
内容的提问来源于stack exchange,提问作者Patrick_Chong
相关产品推荐
相关产品推荐

