Leetcode/leetcode46

46. Permutations

题目

解题思路

  1. 先将一个数组从小到大排序
  2. 从有向左查找第一个递减的数
  3. 再次2找的的数右边查比该数大的最小的数
  4. 步骤2,3找到的数互换位置
  5. 步骤找到的数的后面的数,进行逆转(可以进行排序O(nlogn),也可以逆转O(n)),逆转的时间复杂度比较小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class Solution {
public List<List<Integer>> permute(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
int rht = nums.length - 1;
int j = rht;

list.add(toList(nums));

while(j >= 0) {

j = rht;
while(j-1 >=0 && nums[j] < nums[j-1])j--;
if(j-1 < 0) return list;

int i = j;
while(i<=rht && nums[i] > nums[j-1]) i++;
if(i>rht)i=rht+1;
swap(nums, i-1, j-1);

//Arrays.sort(nums, j, rht+1);

reverse(nums, j, rht);
list.add(toList(nums));


}


return null;
}
public void reverse(int[] nums, int i, int j) {
int mid = (i+j)/2;
if(mid==nums.length-1)return;
if((i+j)%2==1) {
for(int a = mid; a>=i;a--) {
swap(nums, a, 2*mid-a+1);
}
}else {
for(int a = mid-1; a>=i;a--) {
swap(nums, a, 2*mid-a);
}
}
}
public List toList(int[] nums) {
ArrayList<Object> arrayList = new ArrayList<>();
for(Integer e: nums) {
arrayList.add(e);
}
return arrayList;
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static void main(String[] args) {
int[] nums = {2,6,1};

System.out.println(new Solution().permute(nums).toString());
}
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×