【问题标题】:Trying to generate subset of a string using recursion method尝试使用递归方法生成字符串的子集
【发布时间】:2019-06-01 14:10:08
【问题描述】:

尝试在 python 中使用递归实现算法。看起来缺少一些我无法调试的东西。

我的方法是有两个递归分支,并在每次递归时传递一个元素。详情如下:

## input pattern : "ab"
## output pattern : ["", "a", "b", "ab"]

此模式的递归树如下所示

#           "ab" [ROOT]
#                   |
#           -a           +a
#           |             |
#       -b      +b    -b    +b
# =>    ""      "b"     "a"     "ab"

我现有的代码如下:它没有按预期工作。

def gen_subset(slist):
    def helper(slist,i,temp,out):
        if len(slist) == i:
            out.append(temp)
            return()
        else:
            helper(slist,i+1,temp,out)
            temp.append(slist[i])
            helper(slist,i+1,temp,out)

    out = []
    helper(slist,0,[],out)
    return out

s = "ab"
print (gen_subset([c for c in s]))

此代码产生错误的结果。

输出

[['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b'], ['b', 'a', 'b']]

我这里有什么遗漏吗?

【问题讨论】:

    标签: python python-3.x recursion


    【解决方案1】:

    temp.append(slist[i]) 更改为temp = temp + [slist[i]]

    这是因为temp.append() 就地修改了temp 变量。
    相反,我们需要将temp 的副本传递给下一个递归调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2017-01-25
      • 2021-01-30
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多