上回说到全排列,这里进行补充。

运用搜索算法,进行全排列。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
 1 #include<iostream>
 2 
 3 using namespace std;
 4 int a[1000];
 5 
 6 void search(int t)
 7 {
 8   if(t>3)
 9   {
10     for(int i=1;i<=3;i++)
11       cout<<a[i]<<" ";
12     cout<<endl;
13     return;
14   }
15   for(int i=1;i<=3;i++)
16   {
17     a[t]=i;
18     search(t+1);
19   }
20 }
21 
22 int main()
23 {
24   search(1);
25 }

这样一来会发现有重复的这样的话我们只需要筛选一下,运用通数组标记。

 1 #include<iostream>
 2 
 3 using namespace std;
 4 int a[1000],to[1000];
 5 
 6 void search(int t)
 7 {
 8   if(t>3)
 9   {
10     for(int i=1;i<=3;i++)
11       cout<<a[i]<<" ";
12     cout<<endl;
13     return;
14   }
15   for(int i=1;i<=3;i++)
16   {
17     if(to[i]) continue;
18     to[i]=true;
19     a[t]=i;
20     search(t+1);
21     to[i]=false;    
22   }
23 }
24 
25 int main()
26 {
27   search(1);
28 }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄