forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1.java
62 lines (48 loc) · 1.56 KB
/
Solution1.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
/// Source : https://leetcode.com/problems/permutations/description/
/// Author : liuyubobobo
/// Time : 2017-11-18
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
/// Most Naive Recursive
/// Time Complexity: O(n^n)
/// Space Complexity: O(n)
public class Solution1 {
private ArrayList<List<Integer>> res;
private boolean[] used;
public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0)
return res;
used = new boolean[nums.length];
LinkedList<Integer> p = new LinkedList<Integer>();
generatePermutation(nums, 0, p);
return res;
}
private void generatePermutation(int[] nums, int index, LinkedList<Integer> p){
if(index == nums.length){
res.add((LinkedList<Integer>)p.clone());
return;
}
for(int i = 0 ; i < nums.length ; i ++)
if(!used[i]){
used[i] = true;
p.addLast(nums[i]);
generatePermutation(nums, index + 1, p );
p.removeLast();
used[i] = false;
}
return;
}
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);
}
}