C++ 递归位置排列算法及其应用
来源:互联网 发布:linux ssh 限定目录 编辑:程序博客网 时间:2024/05/17 08:05
废话不多说,我们先看一下位置排序的算法:
#include <iostream>using namespace std;int n = 0;int m = 2;int l = 0;int a[100];void solve(int l);int main(){cout<<"请输入位数 n "<<endl;cin>>n;solve(l);return 0;}void solve(int l){if(l>=n){for(int i = 0 ; i<n; i++){cout<<a[i];}cout << endl;return;}for(int i = 0 ;i < m;i++){a[l] = i;solve(l+1);}}
运行结果如下:
请输入位数 n
4
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
我们可以把这个算法应用到这样一个例子中:
递归求一个集合的所有子集:
代码如下:
#include <iostream>#include<vector>#include <stdio.h>using namespace std;void solve(int l);int n, m;int mat[100];vector<string> collection;int main(){ string firstElement; string element; int mcount = 1; cout << "Please input the element , end by #end" << endl; cin >> firstElement; while(firstElement != "#end") { element = firstElement; cout << "The element "<<mcount<< " you input is "+ element<< endl; collection.push_back(element); //cout << collection[mcount-1]; cout << "Please input the next element , end by #end" << endl; cin >> firstElement; }n = collection.size(); m = 2; solve(0); return 0;}void solve(int l)//l=0{ int i; if(l >= n)//n=4 {printf("{"); for(i=0; i<n; ++i) { if(mat[i] == 1) { cout<< collection[i] << " "; } } printf("}\n"); return; } for(i=0; i<m; ++i)//m=2 { mat[l] = i; solve(l+1); }}
运行结果如下:
Please input the element , end by #end
a
The element 1 you input is a
Please input the next element , end by #end
b
The element 1 you input is b
Please input the next element , end by #end
c
The element 1 you input is c
Please input the next element , end by #end
#end
{}
{c }
{b }
{b c }
{a }
{a c }
{a b }
{a b c }
10 0
- C++ 递归位置排列算法及其应用
- 递归算法及其应用
- 递归算法及其应用
- 递归应用-全排列
- 全排列递归算法
- 全排列递归算法
- 全排列算法-递归
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 全排列递归算法
- 递归算法---全排列
- 全排列递归算法
- 全排列递归算法
- 修改网卡mac地址的思考
- 约瑟夫环
- File的getPath()和getAbsolutePath()和getCanonicalPath()的区别
- 联想S720/S720i通刷刷机包 Vibe V1.0
- ubuntu 14.04 将窗口按钮移到右边
- C++ 递归位置排列算法及其应用
- 新人报道 献上薄礼
- poj 3009 Curling 2.0 (dfs)
- 敏捷开发模式
- 看展览胡月:Testin云测给多数安卓开发者带来实实在在帮助
- 挂接命令(mount)
- 广点通屡次改版,微信“电商化”缺什么?
- __stdcall,__cdecl,__fastcall的区别
- 神奇的String格式化