有1,2,3,4這4個數字,能組成多少個互不相同且無重複數字的三位數,下面是二種解決示例,需要的朋友可以參考下
第一種方法:遞迴
複製**
**如下:
def perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in perms(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
for item in list(perms([1, 2, 3,4])):
print item
結果 複製**
**如下:
[1, 2, 3, 4]
[2, 1, 3, 4]
[2, 3, 1, 4]
[2, 3, 4, 1]
[1, 3, 2, 4]
[3, 1, 2, 4]
[3, 2, 1, 4]
[3, 2, 4, 1]
[1, 3, 4, 2]
[3, 1, 4, 2]
[3, 4, 1, 2]
[3, 4, 2, 1]
[1, 2, 4, 3]
[2, 1, 4, 3]
[2, 4, 1, 3]
[2, 4, 3, 1]
[1, 4, 2, 3]
[4, 1, 2, 3]
[4, 2, 1, 3]
[4, 2, 3, 1]
[1, 4, 3, 2]
[4, 1, 3, 2]
[4, 3, 1, 2]
[4, 3, 2, 1]
第二種方法:python標準庫
複製**
**如下:
import itertools
print list(itertools.permutations([1, 2, 3,4],3))
源**如下:
複製**
**如下:
#coding:utf-8
import itertools
print list(itertools.permutations([1, 2, 3,4],3))
def perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in perms(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
for item in list(perms([1, 2, 3,4])):
print item
遞迴實現全排列python
1.保持a不動,動bcd 2.保持b不動,動cd 3.保持c不動,動d def pailie head string if len string 1 for father string in string pailie head father string,string.replace father...
python集合全排列 python全排列,遞迴
全排列 用遞迴方法 全排列 1 列表只有乙個元素 a 它的全排列只有a。2 列表有兩個元素 a,b 它的全排列為 a,b b,a 3 列表有三個元素 a,b,c 交換ab,b,a,c 對ac進行全排列 4 列表有n個元素,將第乙個元素固定,對剩下n 1個元素進行全排列。將第乙個元素依此與其他元素交換...
全排列實現
參考的是 演算法競賽入門 p185 方法是用乙個額外的陣列a,不斷放入物件到這個陣列中,直到n個為止。include using namespace std int total 0 void permutation char s,char a,int n,int cur total cout end...