【Leetcode】31. Next Permutation 解题报告
题面
https://leetcode.com/problems/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 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
思路:
通过画一个树形图可以发现,每一次如果在下面找不到比自己的节点,说明要跨届了,就是往上一层。如果找到比自己大的,就需要将这个比自己大的当作第一个节点,然后剩下的节点排序。
第一遍(虽然做出来了正确的结果,但是实际上没有完全想明白)‘
class Solution {
public void nextPermutation(int[] nums) {
Integer[] numbers = new Integer[nums.length+1];
numbers[0] = Integer.MAX_VALUE;
for (int i = 1; i < nums.length + 1; i++) {
numbers[i] = nums[i-1];
}
int start = numbers.length - 2;
while (start >= 0) {
int index = heleperFinding(numbers, start);
if (index != -1) {
int temp = numbers[index];
numbers[index] = numbers[start];
numbers[start] = temp;
numbers = helperSorting(numbers, start+1);
break;
} else {
start--;
}
}
for (int i = 0; i < nums.length; i++) {
nums[i] = numbers[i+1];
}
System.out.print("ending");
}
public Integer[] helperSorting(Integer[] numbers, int start) {
Arrays.sort(numbers,start,numbers.length);
return numbers;
}
public int heleperFinding(Integer[] nums, int index) {
Arrays.sort(nums,index+1, nums.length);
for (int i = index+1; i < nums.length; i++) {
if (nums[i] > nums[index]) {
return i;
}
}
return -1;
}
}
这道题应该需要用到backtracking? 怎么用?