dfs生成排列组合模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31736627/article/details/61010183

枚举可重复排列的模板

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. using namespace std;  
  3. int n,m,ans[15];  
  4. int a[15];//待排列的数存储在此  
  5. bool vis[15];  
  6. void dfs(int cnt)//按字典序输出n个数选m个数的所有排列  
  7. {  
  8.     if(cnt==m)  
  9.     {  
  10.         for(int i=0;i<m;i++) cout<<ans[i]<<" ";  
  11.         cout<<endl;  
  12.         return ;  
  13.     }  
  14.     for(int i=0;i<n;i++)  
  15.     {  
  16.         ans[cnt]=a[i];  
  17.         dfs(cnt+1);  
  18.     }  
  19. }  
  20. int main()  
  21. {  
  22.     while(cin>>n>>m)  
  23.     {  
  24.         fill(vis,vis+15,0);  
  25.         for(int i=0;i<n;i++) cin>>a[i];  
  26.         dfs(0);  
  27.     }  
  28.     return 0;  
  29. }  
枚举不可重复的排列,加个标记数组即可。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. using namespace std;  
  3. int n,m,ans[15];  
  4. int a[15];//待排列的数存储在此  
  5. bool vis[15];  
  6. void dfs(int d,int cnt)//按字典序输出n个数选m个数的所有排列  
  7. {  
  8.     if(cnt==m)  
  9.     {  
  10.         for(int i=0;i<m;i++) cout<<ans[i]<<" ";  
  11.         cout<<endl;  
  12.         return ;  
  13.     }  
  14.     for(int i=0;i<n;i++)  
  15.     {  
  16.         if(!vis[i])  
  17.         {  
  18.             ans[cnt]=a[i];  
  19.             vis[i]=1;  
  20.             dfs(i+1,cnt+1);  
  21.             vis[i]=0;  
  22.         }  
  23.     }  
  24. }  
  25. int main()  
  26. {  
  27.     while(cin>>n>>m)  
  28.     {  
  29.         fill(vis,vis+15,0);  
  30.         for(int i=0;i<n;i++) cin>>a[i];  
  31.         dfs(0,0);  
  32.     }  
  33.     return 0;  
  34. }  

枚举组合。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. using namespace std;  
  3. int n,m,ans[15];  
  4. int a[15];//待排列的数存储在此  
  5. bool vis[15];  
  6. void dfs(int d,int cnt)//按字典序输出n个数选m个数的所有组合  
  7. {  
  8.     if(cnt==m)  
  9.     {  
  10.         for(int i=0;i<m;i++) cout<<ans[i]<<" ";  
  11.         cout<<endl;  
  12.         return ;  
  13.     }  
  14.     for(int i=d;i<n;i++)  
  15.     {  
  16.         ans[cnt]=a[i];  
  17.         dfs(i+1,cnt+1);  
  18.     }  
  19. }  
  20. int main()  
  21. {  
  22.     while(cin>>n>>m)  
  23.     {  
  24.         fill(vis,vis+15,0);  
  25.         for(int i=0;i<n;i++) cin>>a[i];  
  26.         dfs(0,0);  
  27.     }  
  28.     return 0;  
  29. }  

猜你喜欢

转载自blog.csdn.net/qq_31736627/article/details/61010183