python全配列

3176 ワード

1.      itertools
2.    
[1,2,3] 
   1    1   :[1,2,3]
     1  ,  [2,3]   [1,2,3] [1,3,2]    ;          
   2    1   :[2,1,3]
     2  ,  [1,3]   [2,1,3] [2,3,1]    ;          
   3    1   :[3,2,1]
     3  ,  [2,1]   [3,1,2] [3,2,1]    ;

print '1 instant:'
for i in itertools.permutations([1,2,3],3): print i
print '2 recursive:'
def permut(num,begin,end):
    if begin==end:
        print num
    else:
        i=begin
        for j in xrange(begin,end):
            num[j],num[i]=num[i],num[j]
            permut(num,begin+1,end)
            num[j],num[i]=num[i],num[j]
num=[1,2,3]  
permut(num,0,len(num))  
'''
2 recursive:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
'''