首页 > 解决方案 > 在发现所有状态之前终止递归

问题描述

我编写了以下函数,程序的输出是正确的。但是,程序在进行递归时会发现所有可能的状态,这意味着程序可以更高效地完成。基本上,我需要递归在输出时终止,True而不是发现其他状态。任何想法表示赞赏!

checked_strings = []

# idx - current index of string a
# input string a
# output string b
def abbreviation(idx, a, b):
    if a in checked_strings:
        return False
    if idx == len(a):
        return a == b
    flag1 = flag2 = False
    if a[idx].islower():
        new_string1 = a[:idx] + a[idx+1:]
        flag1 = abbreviation(idx, new_string1, b)
        if not flag1:
            checked_strings.append(new_string1)
        new_string2 = a[:idx] + a[idx].upper() + a[idx+1:]
        flag2 = abbreviation(idx + 1, new_string2, b)
        if not flag2:
            checked_strings.append(new_string2)
    return flag1 or flag2 or abbreviation(idx + 1, a, b)

问题描述如下:

给定两个字符串abb大写)。使用以下规则查找是否可以b从字符串中获取字符串:a

  1. 如果字符串的字符是小写的,那么您可以删除它。

  2. 如果字符串的字符是小写的,那么你可以把这个字符变成大写。

  3. 字符可以跳过。

输入如下:

1
daBcd
ABC

虽然输出应该是:

true 

标签: pythonrecursiontermination

解决方案


checked_strings = []

# idx - current index of string a
# input string a
# output string b
def abbreviation(idx, a, b):
    if a in checked_strings:
        return False
    if idx == len(a):
        return a == b
    flag1 = flag2 = False
    if a[idx].islower():
        new_string1 = a[:idx] + a[idx+1:]
        flag1 = abbreviation(idx, new_string1, b)
        if flag1:
            return True
        else
            checked_strings.append(new_string1)
        new_string2 = a[:idx] + a[idx].upper() + a[idx+1:]
        flag2 = abbreviation(idx + 1, new_string2, b)
        if flag2:
            return True
        else
            checked_strings.append(new_string2)
    return abbreviation(idx + 1, a, b)

当其中一个标志为 True 时,您可以立即返回它。


推荐阅读