标签:style blog io color sp for on div log
给定正整数n,求1,2,3,...,n的全排列
解法一:递归,结果并不为字母序排列。
void Helper(vector<int> v, int low, int high) { if(low == high) { for(int i = 0; i < v.size(); i ++) cout << v[i]; cout << endl; } else { for(int i = low; i <= high; i ++) { swap(v[low], v[i]); Helper(v, low+1, high); swap(v[low], v[i]); } } } void permutation(int n) { vector<int> v(n,0); for(int i = 0; i < n; i ++) v[i] = i+1; Helper(v, 0, n-1); }
解法二:algorithm库中的next_permutation函数,结果按字母序排列
void permutation(int n) { vector<int> v(n,0); for(int i = 0; i < n; i ++) v[i] = i+1; do { for(int i = 0; i < v.size(); i ++) cout << v[i]; cout << endl; }while(next_permutation(v.begin(),v.end())); }
标签:style blog io color sp for on div log
原文地址:http://www.cnblogs.com/ganganloveu/p/4156257.html