C#LeetCode刷题之#31-下一个排列（Next Permutation）

问题

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

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 and use only constant 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,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

示例

```public class Program {

public static void Main(string[] args) {
var nums = new int[] { 1, 6, 9, 4, 2, 1 };

NextPermutation(nums);
ShowArray(nums);

}

private static void ShowArray(int[] nums) {
foreach(var num in nums) {
Console.Write(\$"{num} ");
}
Console.WriteLine();
}

public static void NextPermutation(int[] nums) {
var i = 0;
var j = 0;
var n = nums.Length;
//从右往左找到第一个“逆行”的数字，此案例是 6，索引为 i
//从右往左再找到第一个比“逆行数字”大的数字，此案例是 9
//交换6、9，并将索引 i 之后的部分反转（原来为从大到小，改成从小到大）
for(i = n - 2; i >= 0; i--) {
if(nums[i + 1] > nums[i]) {
for(j = n - 1; j >= i; j--) {
if(nums[j] > nums[i]) break;
}
var swap = nums[i];
nums[i] = nums[j];
nums[j] = swap;
Array.Reverse(nums, i + 1, nums.Length - (i + 1));
//可以返回了
return;
}
}
//如果已经是最大的了，直接反转成最小的
Array.Reverse(nums, 0, nums.Length);
}

}
```

```1 9 1 2 4 6
```