cb47a_c++_STL_算法_排列组合next_prev_permutation
cb47a_c++_STL_算法_排列组合next_prev_permutation
使用前必须先排序。必须是 1,2,3或者3,2,1.否者结果不准确。如果, 1,2,4,6.这样数据不会准确
next_permutation()//原始数据是从小到大的, 1,2,3
prev_permutation() //原始数据是从大到小的,比如 3 ,2 ,1,则可以使用这个算法。
3个数字就6种组合。
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
返回值是ture,则还有下一个组合
false,则没有下一个组合了。
1 /*cb47a_c++_STL_算法_排列组合next_prev_permutation 2 3 使用前必须先排序。必须是 1,2,3或者3,2,1.否者结果不准确。如果, 1,2,4,6.这样数据不会准确 4 next_permutation()//原始数据是从小到大的, 1,2,3 5 prev_permutation() //原始数据是从大到小的,比如 3 ,2 ,1,则可以使用这个算法。 6 7 3个数字就6种组合。 8 1 2 3 9 1 3 2 10 2 1 3 11 2 3 1 12 3 1 2 13 3 2 1 14 15 返回值是ture,则还有下一个组合 16 false,则没有下一个组合了。 17 */ 18 19 #include <iostream> 20 #include <algorithm> 21 #include <vector> 22 23 24 using namespace std; 25 26 template <typename TT8> 27 void print8(TT8 &ivec) 28 { 29 for (TT8::iterator iter=ivec.begin();iter!=ivec.end();++iter) 30 cout << *iter << ' '; 31 cout << endl; 32 } 33 34 int main() 35 { 36 vector<int> ivec; 37 ivec.push_back(1); 38 ivec.push_back(2); 39 ivec.push_back(3); 40 41 print8(ivec); 42 43 //next_permutation(ivec.begin(),ivec.end());//1 3 2,第二个组合 44 //print8(ivec); 45 //next_permutation(ivec.begin(), ivec.end());//2 1 3 第三个组合 46 //print8(ivec); 47 cout << "用循环列出所有的排列组合" << endl; 48 while (next_permutation(ivec.begin(), ivec.end())) 49 { 50 print8(ivec); 51 } 52 cout << "---------------" << endl; 53 vector<int> ivec2; 54 ivec2.push_back(4); 55 ivec2.push_back(3); 56 ivec2.push_back(2); 57 ivec2.push_back(1); 58 59 print8(ivec2); 60 cout << "---------------" << endl; 61 while (prev_permutation(ivec2.begin(), ivec2.end())) 62 { 63 print8(ivec2); 64 } 65 66 67 68 return 0; 69 }
欢迎讨论,相互学习。
cdtxw@foxmail.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)