主要思路:
每次循环,取出一个元素添加的结果数组中,而对剩余的元素进行相同的全排列操作。终止条件:剩余的元素为1。
如[1,2,3,4]的全排列,可以看成是将1或2或3或4(for)放在固定位置,[2,3,4],[1,3,4],[1,2,4],[1,2,3]的全排列,以此类推,[2,3,4]的全排列,可以看成是将2或3或4放在固定位置,[3,4],[2,4],[2,3]的全排列,直到数组中仅有一个元素为止。
import copy
all = [1,2,3,4]
result = []
def fun_fron(remain_list, res_list):
if len(remain_list) == 1:
res_list.append(remain_list[0])
print res_list
result.append(res_list)
else:
for j in xrange(len(remain_list)):
remain_list_c = copy.deepcopy(remain_list)
res_list_c = copy.deepcopy(res_list)
twp = remain_list_c.pop(j)
res_list_c.append(twp)
fun_fron(remain_list_c,res_list_c)
fun_fron(all,[])
print len(result)