Permutation Of Array problem leetCode
Given an array nums of distinct integers, return all the possible
permutations
. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
generatePermutations(nums, 0, result);
return result;
}
private void generatePermutations(int[] nums, int start, List<List<Integer>> result) {
if (start == nums.length) {
result.add(convertToList(nums)); // Convert array to list and add to result
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
generatePermutations(nums, start + 1, result);
swap(nums, start, i); // Backtrack
}
}
private List<Integer> convertToList(int[] nums) {
List<Integer> list = new ArrayList<>();
for (int num : nums) {
list.add(num);
}
return list;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
Comments
Post a Comment