a524. 手機之謎 5/16/2025

解法一、DFS

✅ 完整代碼

評分結果(參考) : AC (12ms, 320KB)

#include <bits/stdc++.h>
using namespace std;

int n;

void dfs(string& s, int k, vector<bool>& v){
    if(k == n) cout << s << "\n";

    for(int i=n; i>0; i--){
        if(!v[i]){
            s[k] = '0'+i;
            v[i] = true;
            dfs(s, k+1, v);
            v[i] = false;
        }
    }    
}

int main(){
    ios::sync_with_stdio();
    cin.tie(nullptr);
    
    while(cin >> n){
        string s(n, '_');
        vector<bool> v(n+1, false);
        dfs(s, 0, v);
    }
    
    return 0;
}