Std::next_permutation and STD are available in C + + STL::p rev_permutation can get a full array of numbers or characters , where std::next_permutation provides ascending , std::p rev_permutation provides descending order .
1.std::next_permutation function prototypes
Template <class bidirectionaliterator>
BOOL Next_permutation (bidirectionaliterator First, Bidirectionaliterator last);
Template <class Bidirectionaliterator, class compare>
BOOL Next_permutation (Bidirectionaliterator First,bidirectionaliterator last, Compare comp);
Description: Next_permutation, rearranging elements in the range [first, last] returns a large combination of the next value arranged in the dictionary order .
Return value: If there is a higher arrangement, it rearranges the element and returns true if it is not possible (because it is already in the largest possible arrangement), it sorts the elements in ascending order, and returns false.
2. Algorithm implementation principle
See: Http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4
Algorithm Description:
1. Look for two adjacent elements from the rear
The 1th element I, the 2nd element J (from the number of i<j), and a
2, and then looking forward from the end of the first element greater than I K. Swap the I, k
3, [j,last) range of elements inversion ( inverted arrangement )
Cases:
Small l time limit for D:4000 ms | Memory limit:65535 KB Difficulty:2
-
Describe
-
One day TC's Marina to find ACM small L play Three Kingdoms kill, but this will be small l busy mile, do not want to play with the marina, but also afraid of the marina, the small l to marina out a topic want to baffle marina (small l very D bar), there is a number n (0<n<10), write 1 to N of the whole arrangement, then marina a little embarrassed,,, Smart can you help Marina to the rescue?
-
Input
-
The first line enters a number n (0<n<10), which indicates that there are n sets of test data. The following n lines enter multiple sets of input data, each set of input data is an integer x (0<x<10)
-
Output
-
Output all combinations in a specific order. Specific order: The values in each combination are arranged from small to large, and the combinations are arranged in dictionary order.
-
Sample input
-
223
-
Sample output
-
1221123132213231312321
1#include <cstdio>2#include <algorithm>3 4 using namespacestd;5 inta[]={1,2,3,4,5,6,7,8,9};6 intMain ()7 {8 intT;9scanf"%d", &t);Ten while(t--){ One intN; Ascanf"%d", &n); - //for (int i = 0; i < n; i++) { - //A[i] = i + 1; the // } - Do - { - for(inti =0; I < n; i++){ +printf"%d", A[i]); - } +printf"\ n"); A} while(Next_permutation (A, A +n)); at } - - return 0; -}
Character:
1#include <iostream>2#include <algorithm>3#include <string>4 5 using namespacestd;6 7 intMain ()8 {9 stringstr;TenCIN >>str; One sort (Str.begin (), Str.end ()); Acout << str <<Endl; - while(Next_permutation (Str.begin (), Str.end ())) - { thecout << str <<Endl; - } - return 0; -}
C + + full permutation function Nyoj 366