8 条题解
-
0
#include<bits/stdc++.h> using namespace std;
int num[10],str[10]; int ans=0; void dfs(int n,int n2){
for(int i=1;i<=n2;i++) { if(str[i]!=0) continue; str[i] =1; num[n]=i; dfs(n+1,n2); str[i]=0; }
if(n==n2) { for(int i=1;i<=n2;i++) { cout<<num[i]<<' '; } cout<<endl; }
} int main() { int n2; cin>>n2; dfs(1,n2); return 0; }
-
0
#include<iostream> #include<algorithm> #include<cmath> #include<cstdio> #include<vector> using namespace std; const int N=12; int used[N]; int nums[N]; vector<int> res; int n; void dfs(int countNum){ if(countNum>n){ for(auto temp:res) cout<<temp<<" "; cout<<endl; return; } for(int i=0;i<n;i++){ if(used[i]) continue; // 标记为被使用过 used[i]=1; res.push_back(nums[i]); dfs(countNum+1); used[i]=0; res.pop_back(); } } int main(){ cin>>n; for(int i=0;i<n;i++) nums[i]=i+1; dfs(1); return 0; }
-
0
提供两种解法:
next_permutation
#include <bits/stdc++.h> using namespace std; const int N = 20; int a[N]; int n; int main(){ scanf("%d",&n); for (int i = 1; i <= n; ++i) { a[i] = i; } do{ for (int i = 1; i <= n; ++i) { printf("%d ",a[i]); } printf("\n"); }while(next_permutation(a + 1,a + n + 1)); return 0; }
DFS
#include <bits/stdc++.h> using namespace std; const int N = 20; int vis[N]; int a[N]; int n; void dfs(int x){ if (x > n) { for (int i = 1; i <= n; ++i) { printf("%d ",a[i]); } printf("\n"); } for (int i = 1; i <= n; ++i) { if(!vis[i]) { vis[i] = 1; a[x] = i; dfs(x + 1); a[x] = 0; vis[i] = 0; } } } int main(){ scanf("%d",&n); dfs(1); return 0; }
-
0
n = int(input()) nums = [i for i in range(1,n+1)] res = [] path = [] used = [0]*n def dfs(nums,path,used,n): if len(path) == n: print(*path) for i in range(n): if used[i]: continue used[i] = 1 path.append(nums[i]) dfs(nums,path,used,n) path.pop() used[i] = 0 dfs(nums,path,used,n)
-
0
#include <bits/stdc++.h> using namespace std; int a[20], x, n;
int b[20];
void dfs(int x) { if (x > n) { for (int i = 1; i < n; i++) cout << a[i] << " "; cout << a[n] << endl; return; } for (int i = 1; i <= n ; i++) {
if (b[i] == 0) { b[i] = 1; a[x] = i; dfs(x + 1); b[i] = 0; } }
}
int main() { cin >> n; dfs(1); return 0; }
-
0
#include <cstdio> #include <vector> #include <functional> using namespace std; int main() { int n; scanf("%d", &n); vector<char> ita(n + 1, 0); vector<int> res; function<void()> dfs = [&]() { if (res.size() >= n) { for (int& it : res) printf("%d ", it); printf("\n"); return; } for (int i = 1; i <= n; ++i) { if (!ita[i]) { // 是否已经放过 ita[i] = 1; res.push_back(i); // 放 dfs(); res.pop_back(); // 不放 ita[i] = 0; } } }; dfs(); return 0; }
- 1
信息
- ID
- 82
- 时间
- 2000ms
- 内存
- 512MiB
- 难度
- 5
- 标签
- 递交数
- 399
- 已通过
- 155
- 上传者