-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
73 lines (63 loc) · 1.69 KB
/
Copy pathPermutations.java
File metadata and controls
73 lines (63 loc) · 1.69 KB
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
63
64
65
66
67
68
69
70
71
72
package Lists;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @description: 描述 Medium
* @author: dekai.kong
* @date: 2018-12-10 11:20
* @from https://leetcode.com/problems/permutations/
* Given a collection of distinct integers, return all possible permutations.
*
* Example:
*
* Input: [1,2,3]
* Output:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*/
public class Permutations {
public Permutations() {
}
/**
* Runtime: 2 ms, faster than 99.96% of Java online submissions for Permutations.
* @param nums
* @return
* 递归法
*/
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> rst = new ArrayList<>();
List<Integer> list = new ArrayList<>();
doRecursive(0,nums,list,rst);
return rst;
}
public void doRecursive(int curinx,int[] nums,List<Integer> list,List<List<Integer>> rst){
if(curinx == nums.length){
rst.add(new ArrayList<>(list));
}else{
for (int i = curinx; i < nums.length; i++) {
int temp;
if(i!=0){ //如果不是第一个
temp = nums[i];
nums[i] = nums[0];
nums[0] = temp;
}
list.add(nums[curinx]);
doRecursive(0,Arrays.copyOfRange(nums,curinx+1,nums.length),list,rst);
list.remove(list.size()-1);
}
}
}
@Test
public void test() {
// System.out.println(permute(new int[]{1,2,3,4}));
System.out.println(permute(new int[]{1,1,2}));
}
}