forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
65 lines (50 loc) · 1.55 KB
/
Solution2.java
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
/// Source : https://leetcode.com/problems/permutations/description/
/// Author : liuyubobobo
/// Time : 2017-11-18
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
/// Recursive get all the permutations in place
/// Time Complexity: O(n!)
/// Space Complexity: O(n)
public class Solution2 {
private ArrayList<List<Integer>> res;
public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0)
return res;
generatePermutation(nums, 0);
return res;
}
private void generatePermutation(int[] nums, int index){
if(index == nums.length){
List<Integer> list = new ArrayList<Integer>();
for(int i : nums)
list.add(i);
res.add(list);
return;
}
for(int i = index ; i < nums.length ; i ++){
swap(nums, i, index);
generatePermutation(nums, index + 1);
swap(nums, i, index);
}
return;
}
private void swap(int[] nums, int i, int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private static void printList(List<Integer> list){
for(Integer e: list)
System.out.print(e + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = (new Solution1()).permute(nums);
for(List<Integer> list: res)
printList(list);
}
}