DFS -1

从 1 $\sim $ n 这 n 个整数中随机选取任意多个,输出所有可能的选择方案。

输入格式

输入一个整数 n。

输出格式

每行输出一种方案。

同一行内的数必须升序排列,相邻两个数用恰好 111 个空格隔开。

对于没有选任何数的方案,输出空行。

本题有自定义校验器(SPJ),各行(不同方案)之间的顺序任意。

数据范围

1 ≤ n ≤15

输入样例:

3

输出样例:

3
2
2 3
1
1 3
1 2
1 2 3

1)非升序暴力:

点击查看代码
#include <bits/stdc++.h>

using namespace std;

const int N = 140;

int n,a[N];
bool st[N];

void dfs(int x,int hole) // cnt  current time print how long 
{
    if( x > hole )
    {
        for(int i = 1; i <= hole ; i++)
        {
            cout << a[i] << ' ';
        }
        cout << endl;
        return ;
    }
    for(int i = 1 ; i <= n ; i ++)
    {
       if(!st[i])
       {
           st[i] = true;   a[x] = i; 
           dfs(x + 1,hole);
           st[i] = false;  a[x] = 0;
       }
    }
}

int main()
{
    cin >> n;
    cout << endl;
    for(int i = 1 ; i<= n; i++)
        dfs(1,i);
    
    return 0;
}

2)升序dfs
到底有什么不同

	void dfs(int x,int hole,int current) // cnt  current time print how long 
	{
		if( x > hole )
		{
			for(int i = 1; i <= hole ; i++)
				cout << a[i] << ' ';
			cout << endl;
			return ;
		}
		for(int i = current ; i <= n ; i ++)
		{
		  if( !st[i] )
		  {
			  st[i] = true;   a[x] = i; 
			  //dfs(x + 1 , hole , current + 1);
			  dfs(x + 1 , hole , i + 1);
			  st[i] = false;  a[x] = 0;
		  }
		}
	}
点击查看代码
#include <bits/stdc++.h>

using namespace std;

const int N = 140;

int n,a[N];
bool st[N];

void dfs(int x,int hole,int current) // cnt  current time print how long 
{
    if( x > hole )
    {
        for(int i = 1; i <= hole ; i++)
            cout << a[i] << ' ';
        cout << endl;
        return ;
    }
    for(int i = current ; i <= n ; i ++)
    {
      if( !st[i] )
      {
          st[i] = true;   a[x] = i; 
          //dfs(x + 1 , hole , current + 1);
          dfs(x + 1 , hole , i + 1);
          st[i] = false;  a[x] = 0;
      }
    }
}

int main()
{
    cin >> n;
    cout << endl;
    for(int i = 1 ; i<= n; i++)
        dfs(1,i,1);
    
    return 0;
}
posted @ 2022-02-17 02:31  HarySeldon  阅读(70)  评论(0)    收藏  举报