Files
python/C++专题课程/全排列/二进制思想求全排列.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

59 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}