題目地址:https://leetcode.com/problems/next-permutation/spa
題目分析:首先須要找到最後一個順序對中的前一個數,爲何須要找到最後一個順序對中的前一個數?由於這個數後面都是逆序,也就是說須要從這個數後面找到最後一個比這個數大的數,並與這個數進行交換,交換以後後面部分是逆序的,此時須要將後面這部分進行反轉,此時就是next permutation了。code
題目解答:blog
public class Solution { public void nextPermutation(int[] num) { int lastPS = -1; int i = 0; while(i < num.length - 1){ if(num[i]<num[i+1]){ lastPS = i; } i++; } if(lastPS == -1){ for(int k = 0;k<num.length/2;k++){ int temp = num[k]; num[k] = num[num.length-1-k]; num[num.length-1-k] = temp; } return; } int lastExchange = lastPS+1; while(lastExchange<num.length&&num[lastExchange]>num[lastPS]) lastExchange++; lastExchange--; int temp = num[lastPS]; num[lastPS] = num[lastExchange]; num[lastExchange] = temp; for(int j = lastPS + 1;j<=(lastPS+num.length)/2;j++){ temp = num[j]; num[j] = num[num.length-j+lastPS]; num[num.length-j+lastPS] = temp; } return; } }