3 solutions
-
1
1.递归调用(dfs):
#include<bits/stdc++.h> using namespace std; void permutation(vector<int> a, int begin_, int end_){ if(begin_ == end_){ for(auto i:a)cout<<i<<" "; cout<<endl; return; } for(int i=begin_;i<=end_;i++){ swap(a[i],a[begin_]); sort(a.begin()+begin_+1,a.begin()+end_+1); permutation(a, begin_+1, end_); swap(a[i],a[begin_]); } } int main(){ int n; cin>>n; vector<int> a; for(int i=1;i<=n;i++){ a.push_back(i); } sort(a.begin(),a.end()); permutation(a, 0, n-1); //传入的数组,起始下标 return 0; }
2、stl库中的next_permutation函数:
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; vector<int> a; for(int i=1;i<=n;i++){ a.push_back(i); } sort(a.begin(),a.end()); do { for(auto i:a)cout<<i<<" "; cout<<endl; } while(next_permutation(a.begin(),a.end())); return 0; }
Information
- ID
- 45
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 5
- Tags
- # Submissions
- 338
- Accepted
- 122
- Uploaded By