Last active
August 29, 2015 14:16
-
-
Save dmnugent80/fc2578f86b3aff355497 to your computer and use it in GitHub Desktop.
Permutations of Integer Array, return List of ArrayLists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public List<List<Integer>> permute(int[] num) { | |
| boolean[] used = new boolean[num.length]; | |
| for (int i = 0; i < used.length; i ++) used[i] = false; | |
| List<List<Integer>> output = new ArrayList<List<Integer>>(); | |
| ArrayList<Integer> temp = new ArrayList<Integer>(); | |
| permuteHelper(num, 0, used, output, temp); | |
| return output; | |
| } | |
| public void permuteHelper(int[] num, int level, boolean[] used, List<List<Integer>> output, ArrayList<Integer> temp){ | |
| if (level == num.length){ | |
| output.add(new ArrayList<Integer>(temp)); | |
| } | |
| else{ | |
| for (int i = 0; i < num.length; i++){ | |
| if (!used[i]){ | |
| temp.add(num[i]); | |
| used[i] = true; | |
| permuteHelper(num, level+1, used, output, temp); | |
| used[i] = false; | |
| temp.remove(temp.size()-1); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| //Testing: | |
| import java.util.List; | |
| import java.util.ArrayList; | |
| public class Solution { | |
| public static void main(String[] args) | |
| { | |
| int array[]={1,2,3,4,5,6}; | |
| List<List<Integer>> listList = permute(array); | |
| for (List<Integer> list : listList){ | |
| for (Integer i : list){ | |
| System.out.print(i + " "); | |
| } | |
| System.out.println(); | |
| } | |
| } | |
| public static List<List<Integer>> permute(int[] num) { | |
| boolean[] used = new boolean[num.length]; | |
| for (int i = 0; i < used.length; i ++) used[i] = false; | |
| List<List<Integer>> output = new ArrayList<List<Integer>>(); | |
| ArrayList<Integer> temp = new ArrayList<Integer>(); | |
| permuteHelper(num, 0, used, output, temp); | |
| return output; | |
| } | |
| public static void permuteHelper(int[] num, int level, boolean[] used, List<List<Integer>> output, ArrayList<Integer> temp){ | |
| if (level == num.length){ | |
| output.add(new ArrayList<Integer>(temp)); | |
| } | |
| else{ | |
| for (int i = 0; i < num.length; i++){ | |
| if (!used[i]){ | |
| temp.add(num[i]); | |
| used[i] = true; | |
| permuteHelper(num, level+1, used, output, temp); | |
| used[i] = false; | |
| temp.remove(temp.size()-1); | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment