相关疑难解决方法(0)

理解和可视化递归

我在这里提到了几个关于递归的问题但是我无法理解递归是如何适用于这个特定问题的:递归程序在Python中获取字符串中的所有字符组合:

st= []
def combi(prefix, s):
    if len(s)==0: return 
    else:
        st.append(prefix+s[0])        

        ''' printing values so that I can see what happens at each stage '''
        print "s[0]=",s[0]
        print "s[1:]=",s[1:]
        print "prefix=",prefix
        print "prefix+s[0]=",prefix+s[0]
        print "st=",st

        combi(prefix+s[0],s[1:])
        combi(prefix,s[1:])
        return st

print combi("",'abc')
Run Code Online (Sandbox Code Playgroud)

我已经打印了值,以便我可以看到发生了什么.这是输出:

s[0]= a
s[1:]= bc
prefix= 
prefix+s[0]= a
st= ['a']
s[0]= b
s[1:]= c
prefix= a
prefix+s[0]= ab
st= ['a', 'ab']
s[0]= c
s[1:]= 
prefix= ab
prefix+s[0]= abc
st= ['a', 'ab', 'abc']
s[0]= c
s[1:]= 
prefix= a  ----> How …
Run Code Online (Sandbox Code Playgroud)

python algorithm recursion

7
推荐指数
2
解决办法
3520
查看次数

标签 统计

algorithm ×1

python ×1

recursion ×1