POJ3187 problem solution (DFS full arrangement)

Title description:

Give you two integers, n and m, and synthesize m with the numbers 1-n in the form of Yang Hui's triangle.
Let you deduce the composition with the smallest lexicographic order based on m.
Insert picture description here

  • 16 can be derived from this.

Problem-solving ideas:

Since the lexicographical order is required to be the smallest, we start from the smallest order, enumerate all the bottom layers of 1-n, and deduce whether it is equal to m.

Problem-solving code:

#include<iostream>
#include<vector>
using namespace std;
int n; int final;
int flag[11] = {
    
     0 };
vector<int>temp;
vector<int>tmp;
int f = 0;
void dfs(int step)
{
    
    	
	if (f)
		return;
	if (step == n)
	{
    
    	
		tmp = temp;
		for (int i = 0; i < n - 1; i++)
		{
    
    	
			for(int j=0;j<tmp.size()-i-1;j++)
			tmp[j] = tmp[j] + tmp[j + 1];
		}
		//cout << tmp[0] << endl;
		if (tmp[0] == final)
		{
    
    
			f = 1;
			for (int i = 0; i < temp.size(); i++)
			{
    
    	
				if (i != 0)
					cout << " ";
				cout << temp[i];
			}
			cout << endl;
		}
		return;
	}
	for (int i = 1; i <= n; i++)
	{
    
    
		if (flag[i] == 0)
		{
    
    	
			flag[i] = 1;
			temp.push_back(i);
			dfs(step + 1);
			temp.pop_back();
			flag[i] = 0;
		}
	}
}
int main()
{
    
    	

	cin >> n >> final;
		memset(flag, 0, sizeof(flag));
		f = 0;
		dfs(0);
	return 0;
}

Guess you like

Origin blog.csdn.net/stn54999/article/details/114154216