4 条题解

  • 0
    @ 2022-10-2 10:46:09

    #include<bits/stdc++.h> using namespace std; int n; int h[1000],v[1000]; int dfs(int u) { if(u>n) { for(int i=1;i<=n;i++) { printf("%5d",h[i]); } cout<<endl; return 0; } for(int i=1;i<=n;i++) { if(v[i]==0) { v[i]=1; h[u]=i; dfs(u+1); v[i]=0; } } } int main() { cin>>n; dfs(1); return 0; }

    • 0
      @ 2022-10-2 9:34:05
      #include<bits/stdc++.h>
      using namespace std;
      int a[15];
      bool vis[15];
      int Search(int k){
      //k表示现在在放第k个数 || 我们现在在树的深度为k 
      	int i;
      	if( k > 3 ){
      	//当k=4时,表示我们已经放完 
      		for(i = 1; i <= 3; ++i){
      			cout<<setw(5)<<a[i];
      			//根据题目输出3个格子摆的什么数 
      		}
      		cout<<endl;
      		return 0;
      		//return 0; 和 else 必须有一个 
      	}
      	for(i = 1; i <= 3; ++i)
      	//1,2,3三种算符可以尝试 
      		if(vis[i]){
      		//第i种算符可以使用 
      			vis[i] = false;
      			//标记第i种算符已经使用 
      			a[k] = i;
      			//第k个位置,使用第i种算符 
      			//保存结果 
      			Search(k+1);
      			//去摆第k+1个位置 
      			vis[i] = true;
      			//还原第i种算符
      			a[k] = 0;
      			//第k个位置上现在没有放算符 
      			//恢复结果 
      		}
      	return 0;
      }
      int main(){
      	//数据初始化
      	memset(a, 0, sizeof(a));
      	//每个位置没有放数,置0 
      	memset(vis, true, sizeof(vis));
      	//每种算符都没有使用过,置true
      	
      	//输入 
      	
      	//从第1个位置开始搜索(尝试/暴力模拟) 
      	Search(1);
      	
      	//输出
      	 
      	return 0;
      }
      
      • 0
        @ 2022-7-29 20:08:21
        dfs
        #include<bits/stdc++.h>
        using namespace std;
        long n,i,j,a[10005],b[100005],c[10005];
        void dfs(long k)
        {
        	long i;
        	if(k>n)
        	{
        		for(i=1;i<=n;i++)cout<<setw(5)<<c[i];
        		puts("");
        		return;
        	}
        	for(i=1;i<=n;i++)
        		if(!b[i])
        		{
        			b[i]=1;
        			c[k]=i;
        			dfs(k+1);
        			b[i]=0;
        		}
        }
        int main()
        {
        	cin>>n;
        	dfs(1);
        }
        • 0
          @ 2022-7-15 9:20:05

          STL 里有个函数叫作 next_permutation

          #include <bits/stdc++.h>
          using namespace std;
          const int N = 15;
          int a[N], n;
          int main() {
          	cin >> n;
          	for (int i = 1; i <= n; i ++)
          		a[i] = i;
          	do {
          		for (int i = 1; i <= n; i ++)
          			cout << setw(5) << a[i];
          		cout << '\n';
          	} while (next_permutation(a + 1, a + 1 + n));
          	return 0;
          }
          
          • 1

          信息

          ID
          129
          时间
          1000ms
          内存
          256MiB
          难度
          4
          标签
          (无)
          递交数
          105
          已通过
          45
          上传者