Preface there are indeed many full-permutation questions in LeetCode. We have introduced a recursive solution. For details, see the full-permutation algorithm of strings.
This section describes a lexicographic method.
The lexicographic method specifies a sequential relationship between characters in a given character set, and generates each order in sequence. For example, if the character set {1, 2, 3} is in full Lexicographic Order: 123,132,213,231,312,321
Example:
The algorithm flow is as follows: from right to left, find the first number that destroys the ascending order from right to left. In the reference example, 3 is the first to destroy the ascending sequence, because 1, 2, 4, 5 is an incremental sequence. from right to left, find the first number greater than step 1. Here is the sequence of numbers after 4 switches the two numbers in reverse order.
This method supports data duplication and is used in C ++ STL
Question Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible Z outcome? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> crop + CjMsMiwxIKH6IDEsMiwzPGJyPgoxLDEsNSCh + crop =" brush: java; "> public class Solution {public void nextPermutation (int [] num) {// special case if (num = null | num. length <= 1) {return;} // find the partition number which violate the increase trend int partition, swapLoc; for (partition = num. length-1; partition-1> = 0; partition --) {if (num [partition-1] <num [partition]) {break;} partition-= 1; // find the first digit which large than Partition number if (partition> = 0) {for (swapLoc = num. length-1; swapLoc> partition; swapLoc --) {if (num [swapLoc]> num [partition]) {break ;}} // swap partition number and change number int tmp = num [partition]; num [partition] = num [swapLoc]; num [swapLoc] = tmp ;} // reverse all the digit on the right of partition index for (int I = partition + 1, j = num. length-1; I <j; I ++, j --) {int tmp = num [I]; num [I] = num [j]; num [j] = tmp ;}}}