Permutation

问题描述:

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

 

C++ STL中提供了next_permutation()函数,在OJ中可以很容易的实现,下面直接实现了STL 中next_permutation()函数

 1 #include 
 2 #include   //next_permutaion,iter_swap,reverse 
 3 using std::vector;
 4 
 5 namespace ns {
 6     template <class BidirectionalIterator>
 7     bool next_permutation (BidirectionalIterator first,
 8                          BidirectionalIterator last)
 9     {
10         if(first == last)  return false;  //empty
11 
12         BidirectionalIterator i = last;
13         if((--i)==first)   return false;  //just one element
14 
15         while(i != first)
16         {
17             auto t = i;
18             --i;
19             if(*i < *t)
20             {
21                 auto j = last;
22                 while(!(*--j > *i));
23                 iter_swap(i,j);
24                 reverse(t, last);
25                 return true;
26             }
27         }
28     reverse(first, last);
29     return false;
30     }
31 } 
32 
33 class Solution {
34 public:
35     vectorint>> permute(vector<int>& nums) {
36         sort(nums.begin(), nums.end());
37         vectorint>> res;
38         do{
39             res.push_back(nums);
40         }while(ns::next_permutation(nums.begin(), nums.end()));
41         return res;
42     }
43 };
44 
45 int main()
46 {
47     vector<int> v{1,2,3};
48     vectorint>> res;
49     Solution s;
50     res = s.permute(v);
51 
52     return 0;
53 }

 方法二:递归实现

 1 #include 
 2 #include    
 3 #include 
 4 using std::vector;
 5 
 6 class Solution {
 7 public:
 8     vectorint>> permute(vector<int>& nums) {
 9         sort(nums.begin(), nums.end());
10         vectorint>> res;
11         vector<int> v;
12         dfs(nums,v,res);
13         return res;
14     }
15 private:
16     void dfs(vector<int>& nums,vector<int>& v,vectorint>>& res)
17     {
18         if(v.size() == nums.size())
19         {
20             res.push_back(v);
21             return;
22         }
23         for(auto i : nums)
24         {
25             auto it = find(v.begin(),v.end(),i);
26             if(it == v.end())
27             {
28                 v.push_back(i);
29                 dfs(nums,v,res);
30                 v.pop_back();
31             }
32         }
33     }
34 };
35 
36 int main()
37 {
38     vector<int> v{1,2,3};
39     vectorint>> res;
40     Solution s;
41     res = s.permute(v);
42     for (int i = 0; i < res.size(); ++i)
43     {
44         for(int j=0;j)
45         {
46             cout << res[i][j];
47         }
48         cout << endl;
49     }
50     return 0;
51 }

 

 

 

转载于:https://www.cnblogs.com/wxquare/p/4847492.html

你可能感兴趣的:(Permutation)