这些可以加上题目限制在很多地方用,还有深搜广搜之类的可以借鉴
排列
思路:把所有要排的数放到数组中,然后进行交换,每一个位置的都可以和其他位置的进行交换,但需要规定一个顺序不能重复
还可以直接用库函数next_permutation(a,a+x)
#include <iostream>
using namespace std;
void Perm(int start, int end, int a[]) {
//得到全排列的一种情况,输出结果
if (start == end) {
for (int i = 0; i < end; i++)
cout << a[i] << ' ';
cout << endl;
return;
}
for (int i = start; i < end; i++) {
swap(a[start], a[i]); //交换
Perm(start + 1, end, a); //分解为子问题a[start+1,...,end-1]的全排列
swap(a[i], a[start]); //回溯
}
}
int main() {
int i, n, a[10];
while (cin >> n, n) {
for (i = 0; i < n; i++)
{
a[i] = i + 1;
}
Perm(0, n, a);
}
return 0;
}
组合
采用递归逐个确定
C(n+r+1,r)=C(n+r,r)+C(n+r-1,r-1)+…+C(n+1,1)+C(n,0)
#include <iostream>
using namespace std;
//a为存放待组合的数值,b为用于暂存的数组
//n,m代表从n中取出m个数的组合
// M=m M用于输出
void c(int a[],int b[],int n, int m,const int M)
{
if (m>0)
{
for (int i =n;i>=m;i--)
{
b[m-1]=a[i-1];
//由于确定了当前位置的值
//则下次递归c(n-1,m-1)
c(a,b,i-1,m-1,M);
}
}
else
{
for(int i =0 ; i<M;i++)
cout<<b[i]<<" ";
cout<<endl;
}
}
int main ()
{
int arr[]={0,1,2,3,4,5,6};
int b[7];
c(arr,b,7,5,5);
return 0;
}
子集
#include <iostream>
using namespace std;
//cur用于确定子集的大小
void print_subset(int *A,int n,int cur)
{
if(cur==0) cout << "empty";
for(int i = 0;i<cur;i++)//输出当前子集
cout << A[i] << " ";
cout << endl;
int s = cur? A[cur-1] : 0;//获取当前子集的最小值,当cur为0时防止出现A[-1]
for(int i=s;i<n;i++)//每一次循环都存入一个不同的数进集合,此时变生成了不同的子集
{
A[cur]=i+1;
print_subset(A,n,cur+1);
}
}
int main()
{
int n;
cout<<"输入n"<<endl;
while(cin >> n)
int n;
cout<<"输入n"<<endl;
cin>>n;
int *A=new int[n + 1];
for(int i = 1; i <= n; ++ i)
A[i] = i;
print_subset(A,n,0);
return 0;
}
Ref
https://blog.csdn.net/hf19931101/article/details/79452799
https://blog.csdn.net/a7055117a/article/details/48391923