-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation
More file actions
28 lines (28 loc) · 1.07 KB
/
Permutation
File metadata and controls
28 lines (28 loc) · 1.07 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
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(num.length == 0) return null;
ArrayList<Integer> container = new ArrayList<Integer>();
Integer[] temp = new Integer[num.length];
for(int i=0; i<num.length; i++) temp[i] = num[i];
return helpler(temp, 0, temp.length-1);
}
private ArrayList<ArrayList<Integer>> helpler(Integer[] num, int start, int end){
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(start > end) result.add(new ArrayList<Integer>(Arrays.asList(num)));
else{
for(int i=start; i<=end; i++)
{
swap(num, start, i);
result.addAll(helpler(num, start+1, end));
swap(num, start, i);
}
}
return result;
}
private void swap(Integer[] num, int a, int b){
int temp = num[a];
num[a] = num[b];
num[b] = temp;
}
}