方法一(插入法):
python实现:
#-*- coding:utf-8 -*-
if __name__==‘__main__‘:
l=[1,2,3,4,5]
l_result=[]
for i in l:
s=str(i)
temp=[]
if len(l_result)==0:
temp.append(s)
else:
for j in l_result:
for k in range(len(j)+1):
temp.append(j[:k]+s+j[k:])
l_result=temp
for i in l_result:
temp=[j for j in i]
print temp,
方法二(递归交换):
C++实现:
#include <bits/stdc++.h>
using namespace std;
void print(int a[],int n)
{
for(int i=0;i<=n;i++)
{
cout<<a[i]<<‘ ‘;
}
cout<<endl;
}
void perm(int a[], int k, int m)
{
if (k==m)
{
print(a,m);
return;
}
for (int i=k; i<=m; i++)
{
swap(a[k],a[i]);
perm(a,k+1,m);
swap(a[k],a[i]);
}
}
int main(void)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
perm(a, 0, n-1);
return 0;
}
原文:https://www.cnblogs.com/ybf-yyj/p/9519915.html