leetcode 46 problem permutation in java

Solutions on MaxInterview for leetcode 46 problem permutation in java by the best coders in the world

showing results for - "leetcode 46 problem permutation in java"
Riccardo
21 Feb 2019
1public ArrayList<ArrayList<Integer>> permute(int[] num) {
2	ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
3 
4	//start from an empty list
5	result.add(new ArrayList<Integer>());
6 
7	for (int i = 0; i < num.length; i++) {
8		//list of list in current iteration of the array num
9		ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
10 
11		for (ArrayList<Integer> l : result) {
12			// # of locations to insert is largest index + 1
13			for (int j = 0; j < l.size()+1; j++) {
14				// + add num[i] to different locations
15				l.add(j, num[i]);
16 
17				ArrayList<Integer> temp = new ArrayList<Integer>(l);
18				current.add(temp);
19 
20				//System.out.println(temp);
21 
22				// - remove num[i] add
23				l.remove(j);
24			}
25		}
26 
27		result = new ArrayList<ArrayList<Integer>>(current);
28	}
29 
30	return result;
31}
similar questions
queries leading to this page
leetcode 46 problem permutation in java