Created
July 24, 2020 13:11
-
-
Save willmenn/7950a32ec1b3b89d7482781b75c651d7 to your computer and use it in GitHub Desktop.
Permutation in java
This file contains 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 List<List<Integer>> permute(int[] nums) { | |
List<List<Integer>> res= new ArrayList(); | |
permute(nums, 0, res); | |
return res; | |
} | |
public static int[][] permute(int[] arr, int index, List<List<Integer>> res){ | |
if (index == arr.length){ | |
List<Integer> r = new ArrayList(); | |
for(int num: arr){ | |
r.add(num); | |
} | |
res.add(r); | |
} | |
for(int i=index; i< arr.length ; i++){ | |
swap(arr, index, i); | |
permute(arr, index+1,res); | |
swap(arr, index, i); | |
} | |
return null; | |
} | |
public static void swap(int[] arr, int i, int j){ | |
int a1 = arr[i]; | |
int a2 = arr[j]; | |
arr[i] = a2; | |
arr[j] = a1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment