Next Permutation
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 order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3 → 1,3,23,2,1 → 1,2,31,1,5 → 1,5,1
- void swap(int[] num,int start,int end) {
- int tmp=num[start];
- num[start]=num[end];
- num[end]=tmp;
- }
- public void nextPermutation(int[] num) {
- int nz = num.length;
- if(nz==0) return;
- int i=0;
- for(i=nz-1;i>0;i--) {
- if(num[i-1]<num[i]) {
- int end=nz-1;
- while(num[end] <= num[i-1]) end--;
- swap(num,i-1,end);
- end=nz-1;
- while(i<end) {
- swap(num,i,end);
- i++;
- end--;
- }
- break;
- }
- }
- if(i==0) {
- int end=nz-1;
- while(i<end) {
- swap(num,i,end);
- i++;
- end--;
- }
- }
- }
C++ 代码:提供了reverse函数
- void nextPermutation(vector<int> &num) {
- int len = num.size();
- int i=0;
- int j=0;
- if(len>1) {
- for(i=len-2;i>=0;i--) {
- if(num[i] < num[i+1]) {
- for(j=len-1;j>i;j--) {
- if(num[j]>num[i]) {
- swap(num[i],num[j]);
- break;
- }
- }
- reverse(num.begin()+i+1,num.end());
- break;
- }
- }
- if(i<0) {
- reverse(num.begin(),num.end());
- }
- }
- }
C++ 代码:algorithm中提供了next_permutation函数,返回为bool
- void nextPermutation(vector<int> &num) {
- next_permutation(num.begin(),num.end());
- }

浙公网安备 33010602011771号