Created
September 15, 2019 22:54
-
-
Save forkercat/1dde479cc7a160ad44bb32a13b4b9778 to your computer and use it in GitHub Desktop.
Permutaitons
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
class Solution { | |
public List<List<Integer>> permute(int[] nums) { | |
List<List<Integer>> result = new ArrayList<>(); | |
permute(0, nums, result); | |
return result; | |
} | |
private void permute(int depth, int[] nums, List<List<Integer>> result) { | |
// base case | |
if (depth == nums.length) { | |
List<Integer> list = new ArrayList<>(); | |
for (int val : nums) list.add(val); | |
result.add(list); | |
return; | |
} | |
// enumeration | |
for (int i = depth; i < nums.length; ++i) { | |
swap(nums, depth, i); | |
permute(depth + 1, nums, result); | |
swap(nums, depth, i); | |
} | |
} | |
private void swap(int[] nums, int i, int j) { | |
int temp = nums[i]; | |
nums[i] = nums[j]; | |
nums[j] = temp; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment