Skip to content

Instantly share code, notes, and snippets.

@forkercat
Created September 15, 2019 22:54
Show Gist options
  • Save forkercat/1dde479cc7a160ad44bb32a13b4b9778 to your computer and use it in GitHub Desktop.
Save forkercat/1dde479cc7a160ad44bb32a13b4b9778 to your computer and use it in GitHub Desktop.
Permutaitons
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