4 条题解
-
2
#include <bits/stdc++.h> using namespace std; #define int long long #define endl '\n' const double EPS = 1e-8; const int N = 2e5 + 5; int a[N]; signed main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); int n; cin >> n; vector<int> vec; for (int i = 1; i <= n; i++) { vec.push_back(i); } do { for (int i = 0; i < n; i++) cout << vec[i] << " "; cout << endl; } while (next_permutation(vec.begin(), vec.end())); return 0; } -
1
#include<bits/stdc++.h> using namespace std; typedef long long ll; int n; vector<int> v; bool st[10]; void dfs(int num){ if(num==n){ for(int i=0;i<n;i++){ if(i==0) cout<<v[i]; else cout<<" "<<v[i]; } cout<<"\n"; return; } for(int i=1;i<=n;i++){ if(!st[i]){ st[i]=true; v.push_back(i); dfs(num+1); st[i]=false; v.pop_back(); } } } int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n; dfs(0); return 0; } -
0
JAVA ac代码:
import java.util.*; import java.util.StringTokenizer; import java.io.*; public class Main { static int n; static boolean flag[];//这个数是否被用过 public static void main(String[] args) { n=in.nextInt(); flag=new boolean[n+1]; int[] arr=new int[n];//当前数组 dfs(arr,0); out.close(); } private static void dfs(int[] arr, int i) { //终止条件:i==n,即arr数组中1到n-1位置都被填完了 if(i==n) { for(int j=0;j<n;j++) out.print(arr[j]+" "); out.println(); return; } for(int j=1;j<=n;j++) { //j还没被用过 if(!flag[j]) { flag[j]=true; arr[i]=j;//赋值 dfs(arr,i+1); //回溯 arr[i]=0; flag[j]=false; } } } static FastReader in=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static class FastReader{ static BufferedReader br; static StringTokenizer st; FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next() { String str=""; while(st==null||!st.hasMoreElements()) { try { str=br.readLine(); }catch(IOException e) { throw new RuntimeException(e); } st=new StringTokenizer(str); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
- 1
信息
- ID
- 64
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 入门
- 标签
- 递交数
- 378
- 已通过
- 210
- 上传者