C + + full arrangement and combinatorial algorithm (recursive)

Source: Internet
Author: User

Full arrangement:

The array to be arranged is a[n], which is divided into 0~s-1 and s~n-1 at any time.

Among them, the 0~s-1 is the interval that has been chosen, s~n-1 is the interval to be chosen, the exchange of a number of s~n-1 with s for each choice

#include <iostream>
using namespace std;

void swap (int *a, int i, int j)
{
	int tmp = a[i];
	A[i] =  a[j];
	A[J] = tmp;
}

0~s-1, s~n-1
void perm (int *a, int s, int n)
{
	if (s >= N)
	{for
		(int i = 0; i < n; i++) 
  {
			cout << a[i] << ",";
		}
		cout << Endl;
	}
	else
	{for
		(int i = s; i < n; i++)
		{
			Swap (a, S, i);
			Perm (A, s+1, n);
			Swap (A, S, i);


}} int main ()
{
	int n;
	CIN >> N;
	int a[100];
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	Perm (A, 0, N);
	return 0;
}


Combination algorithm:

All combinations of size m are found from array a[n with size n]

recursive function comp (int *a, int h, int k, int *sub) represents the selection of K in the number of the first h in array A, because you can choose to k-1 the next recursive recursion, so the range of this selection is a[i], where k-1<= i <= h-1, and a[ I] copied to the selected sub[k-1],

And the next recursive comp (A, I, k-1, sub) represents the selection of k-1 in the first number of the array a

#include <iostream>
using namespace std;

int n;
int m;
int num = 0;

void comb (int *a, int h, int k, int *sub)
{
	if (k = = 0)
	{for
		(int i = 0; i < m; i++)
		{
			cout ;< Sub[i] << ",";
		}
		cout << Endl;
		num + +;
	}
	else
	{for
		(int i = h-1 i >= k-1; i--)
		{
			sub[k-1] = a[i];
			Comb (A, I, k-1, sub);

}} int main ()
{
	int n;
	CIN >> n >> m;
	int a[100], sub[100];
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	Comb (A, n, M, sub);
	cout << num << endl;
	return 0;
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.