251. 打印全排列

题目描述

给定一个正整数n,我们取出前n小的正整数,即1~n这n个数字,将他们排列,就一共有n!种排列方案,所有的排列方案统称为n的全排列,现在你需要做的事情就是把n的全排列都输出出来。

解答要求时间限制:1000ms, 内存限制:100MB
输入

输入只有一个数字n(2 <= n <= 7)

输出

输出n的全排列,一共输出n!行,每行输出n个数字,数字之间没有空格,输出的顺序按照数字组成的字符串的字典序从小到大输出。

样例

输入样例 1 复制

3

输出样例 1

123
132
213
231
312
321
提示样例 1
 

思路:dfs暴力即可求解出所有的全排列。

除此以外还有一种方法可以求,大致思想是从后往前找,一直到前一个数字比当前数字小的地方,在后面的数字中选择比前一个数字稍大一点的数字与前一个数字交换,然后将后面的数字从小到大排序即可。

方法1:调用c++接口

// we have defined the necessary header files here for this problem.
// If additional header files are needed in your program, please import here.
#include <vector>
#include <algorithm>
int main()
{  
   vector<int>nums;
   int n;
    cin>>n;
   for(int i = 1;i<= n;i++)
       nums.push_back(i);
    do{
        for(int i = 0;i<n;i++)
        {
            cout<<nums[i];
        }
        cout<<endl;
    }while(next_permutation(nums.begin(),nums.end()));
    
  // please define the C++ input here. For example: int a,b; cin>>a>>b;;  
  // please finish the function body here.  
  // please define the C++ output here. For example:cout<<____<<endl; 
  return 0;
}
以大多数人努力程度之低,根本轮不到去拼天赋~
原文地址:https://www.cnblogs.com/gcter/p/15470676.html