赞
踩
从n数组中选取m个数
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//递归写法
//从n个元素中选取m个 排列有序 123!=321
void Print(int a[],int b[], int n, int m,vector<int>res)
{
if (m == 0)
{
for (auto it = res.begin(); it != res.end(); it++)
cout << *it;
cout << endl;
}
else
{
for (int i = 0; i < n; i++)
{
if (b[i] == 0)
{
res.push_back(a[i]);
b[i] = 1;
Print(a, b, n, m - 1, res);
b[i] = 0;
res.pop_back();
}
}
}
}
//从n个元素中选取m个 排列无序 123=321
void Print1(int a[],int n, int m, int start,vector<int>res)
{
if (m == 0)
{
for (auto it = res.begin(); it != res.end(); it++)
cout << *it;
cout << endl;
}
else
{
for (int i = start; i < n; i++)
{
res.push_back(a[i]);
Print1(a,n, m - 1,i+1,res);
res.pop_back();
}
}
}
//非递归写法 每次从右至左找10组合,交换并使得右边的1是在一起的
/*
11100
11010
11001
10110
10101
10011
01110
01101
01011
00111
*/
void P(int a[], int b[],int n)
{
for (int i = 0; i < n;i++)
if (b[i] == 1) cout << a[i];
cout << endl;
}
void print3(int a[], int n, int m)
{
int b[5] = { 0 };
for (int i = 0; i<m; i++)
b[i] = 1;
int flag = 1;
while (flag>0)
{
P(a, b, n);
int count = 0;//从右至左找到10时右边1的个数
for (flag = n - 1; flag > 0; flag--)
{
if (b[flag] == 0 && b[flag - 1] == 1) break;
if (b[flag]==1)
count++;
}
if (flag > 0)
{
swap(b[flag], b[flag - 1]); //交换10并且使得右边的1是连续的
for (int i = 0; i <=count; i++)
b[flag + i] = 1;
for (int j = flag + count+1; j < n; j++)
b[j] = 0;
}
}
}
int main()
{
int a[5] = { 1, 2, 3, 4, 5 };
print3(a, 5, 3);
return 0;
}
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。