Backtracking Algorithm 1-Combination Problem

[Question]
Find all combinations of r numbers from 1 to n. For example, all combinations of n=5 and r=3 are as follows:

(1) 1
, 2, 3 (2) 1, 2, 4
(3) 1, 2, 5
(4) 1, 3, 4
(5) 1, 3, 5
(6) 1, 4, 5
(7 )2,3,4
(8)2,3,5
(9)2,4,5
(10)3,4,5
According to the backtracking method, the found combinations are stored in the array a in ascending order [0],a[1], .a[r-1], the elements in the combination satisfy the following properties:
(1) a[i+1]>a[i], that is, the next number is greater than the previous number;
(2) a[i]-i<=n-r+1.
According to the backtracking method, the process of finding the solution is described as follows:
First, the condition that the number of combinations is r is not considered for the time being, and the candidate combination starts with only one number. Because the candidate solution satisfies all the conditions except the problem scale, expand its scale and make it satisfy the above condition (1) to obtain candidate combinations 1, 2. Continue this process to get candidate solutions 1, 2, and 3. The candidate solution satisfies all the conditions including the problem size, and is therefore a solution. On the basis of this solution, select the next candidate solution, because the 3 on a[2] is adjusted to 4 and 5 to meet all the requirements of the problem, and solutions 1, 2, 4 and 1, 2, 5 are obtained. Since the adjustment of 5 cannot be continued, it is necessary to backtrack from a[2] to a[1]. You can adjust a[1] from 2 to 3, and try to get solutions 1, 3, 4. Repeat the above-mentioned forward trial and backward tracing until we trace back from a[0], which indicates that all solutions to the problem have been found.

code:

#include<stdio.h>
#include <iostream>
#define MAX 100 
int a[MAX];
void comb(int n, int r)
{
	int i, j;
	i = 0;
	a[i] = 1;
	do
	{
		if (a[i] - i <= n - r + 1) 			/*还可以向前试探*/
		{
			if (i == r - 1)				/*找到一个组合*/
			{
				for (j = 0; j < r; j++)		/*输出一个组合*/
					printf("%4d", a[j]);
				printf("\n");
				a[i]++;
				continue;
			}
			i++;					/*向前试探*/
			a[i] = a[i - 1] + 1;
		}
		else						/*回溯*/
		{
			if (i == 0)				/*找完全部解*/
				return;
			a[--i]++;
		}
	} while (1);
}
void main()
{
	printf("正整数1~5中的3个数的任意组合:\n");
	comb(5, 3);
	system("pause");
}

result:

 

Guess you like

Origin blog.csdn.net/baidu_36669549/article/details/104156704