Topic
Given A collection of numbers, return all possible permutations.
For example,
[following] has the permutations:
[1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Analysis
The problem of the full permutation of all elements in the array of directional quantities.
We know n Element has n! , while STL's underlying files < algorithm > have standard algorithms for arranging elements:
bool next_permutation(BidirectionalIterator beg , BidirectionalIterator end);
This function changes the order of elements within the interval [beg, end] so that they conform to the "next order"
bool prev_permutation(BidirectionalIterator beg , BidirectionalIterator end);
This function changes the order of elements within the interval [beg, end] so that they conform to the "previous order"
If the elements are arranged in a "normal" order (in terms of the dictionary order), the two algorithms return true. The so-called formal order, for next_permutation () is ascending, to Prev_permutation () is descending. So to go through all permutations, you must sort all the elements in ascending or descending order, and then call the Next_permutation () or prev_mutation () function in a circular fashion until the algorithm returns false.
The complexity of the above two algorithms is linear, with a maximum of N/2 switching operations performed.
AC Code
classSolution { Public: vector<vector<int>>Permute ( vector<int>& Nums) { vector<vector<int> >Retif(Nums.empty ())returnRet Sort (Nums.begin (), Nums.end ()); Ret.push_back (Nums); while(Next_permutation (Nums.begin (), Nums.end ())) Ret.push_back (nums);returnRet }};
GitHub test Program source code
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode (permutations)