You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include<iostream>
#include<string.h>
using namespace std;
void Combine(int arr[], int n, int m)
{
if(m > n)
return;
int* pTable = new int[n]; //定义标记buf并将其前m个置1
memset(pTable,0,sizeof(int)*n);
for(int i = 0; i < m; ++i)
pTable[i] = 1;
bool bFind = false;
do
{
for (int i = 0; i < n; i++) //打印当前组合
{
if(pTable[i])
cout << arr[i] << "\t";
}
cout << endl;
bFind = false;
for(int i = 0; i < n-1; i++)
{
if(pTable[i]==1 && pTable[i+1]==0)
{
swap(pTable[i],pTable[i+1]); //调换10为01
bFind = true;
if(pTable[0] == 0) //如果第一位为0则将第i位置之前的1移到最左边如为1则第i位置之前的1就在最左边无需移动
{
for (int k=0, j=0; k < i; k++) //O(n)复杂度使1在前0在后
{
if(pTable[k])
{
swap(pTable[k],pTable[j]);
j++;
}
}
}
break;
}
}
} while (bFind);
delete [] pTable;
}
int main()
{
int arr[] = {1,2,3,4,5,6};
Combine(arr,sizeof(arr)/sizeof(int),3);
return 0;
}