Problem:
Given A collection of numbers, return all possible permutations.
For example,
[1,2,3]The following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].
Hide TagsBacktrackingTest instructions: Given a sequence, outputs all of its permutation combinations
Thinking:
(1) Before writing the next permutation of a sequence, here is the application of the next permutation function to output all possible permutations and combinations
(2) You can also call the STL next_permutation () function, where I re-implement it myself
(3) Title tag hint using backtracking method, also feasible, using depth first search algorithm
Code
Dfs method:
Class Solution {public: vector<vector<int> > Permute (vector<int> &num) { vector< vector<int> > Ret;dfs (ret, num, 0); return ret; } void Dfs (vector<vector<int> >& ret, vector<int>& num, int cur) {if (num.size () = = cur) {Ret.push _back (num);} else{for (int i = cur; i < num.size (); ++i) {swap (Num[cur], num[i]);d FS (ret, NUM, cur+1), swap (Num[cur], num[i]);}}};
Next_permutation Method:
Class Solution {public:vector<vector<int> > Permute (vector<int> &num) {vector<vector& lt;int> > ret; vector<int> tmp; int n = num.size (); int m=1; if (Num.size () <2) {ret.push_back (num); return ret; } sort (Num.begin (), Num.end ()); while (n) {m*=n; n--; } ret.push_back (num);//First insert sorted sequence for (int i=1;i<m;i++)//m-1 {tmp = My_next_permutation (num); Ret.push_back (TMP); num=tmp; } return ret; }protected:/** ideas: From the back to the forward comparison, such as 1-2-3, then the direct reversal after the two to get 1-3-2* for 1-2-4-3, then from the back to the comparison, found 2<4, then looking forward from the first more than 2 of the number 3, Exchange get 1-3-4-2,* The 4-2 parts after the reversal 3 are: 1-3-2-4*/vector<int> my_next_permutation (vector<int> tmp) {Vector<int>::it Erator i = Tmp.end ()-1; Vector<int>::iterator j=i-1; Vector<int>::iterator swap=i; if (*i>*j) {Iter_swap (i,j); return TMP; } while (I!=tmp.begin () && *j>*i) {j--; i--; } if (I==tmp.begin ()) {reverse (Tmp.begin (), Tmp.end ()); return TMP; } while (Swap!=j && *swap<=*j) swap--; Iter_swap (J,swap); Reverse (I,tmp.end ()); return TMP; }};
Leetcode | | 46, permutations