Skip to content

Instantly share code, notes, and snippets.

@almaax33
Created August 4, 2020 02:40
Show Gist options
  • Save almaax33/0a1c933e5dcb990655c56f0fce4d6472 to your computer and use it in GitHub Desktop.
Save almaax33/0a1c933e5dcb990655c56f0fce4d6472 to your computer and use it in GitHub Desktop.
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums == null || nums.length == 0) return result;
List<Integer> listNums = new ArrayList<>(nums.length);
for (int i : nums) { listNums.add(i); }
permute(listNums, 0, nums.length, result);
return result;
}
void permute(List<Integer> nums, int left, int right, List<List<Integer>> result){
if(left == right){
result.add(new ArrayList<>(nums));
}
for (int i = left; i < right; i++) {
swap(nums, left, i);
permute(nums, left+1, right, result);
swap(nums, left, i);
}
}
void swap(List<Integer> nums, int left, int right){
int temp = nums.get(left);
nums.set(left, nums.get(right));
nums.set(right, temp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment