g0001_0100.s0046_permutations.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0046_permutations;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Backtracking
// #Algorithm_I_Day_11_Recursion_Backtracking #Level_2_Day_20_Brute_Force/Backtracking
// #Udemy_Backtracking/Recursion #Big_O_Time_O(n*n!)_Space_O(n+n!)
// #2023_08_11_Time_1_ms_(95.07%)_Space_43.7_MB_(87.98%)
import java.util.ArrayList;
import java.util.List;
/**
* 46 - Permutations\.
*
* Medium
*
* 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]]
*
* **Constraints:**
*
* * `1 <= nums.length <= 6`
* * `-10 <= nums[i] <= 10`
* * All the integers of `nums` are **unique**.
**/
public class Solution {
public List> permute(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List> finalResult = new ArrayList<>();
permuteRecur(nums, finalResult, new ArrayList<>(), new boolean[nums.length]);
return finalResult;
}
private void permuteRecur(
int[] nums, List> finalResult, List currResult, boolean[] used) {
if (currResult.size() == nums.length) {
finalResult.add(new ArrayList<>(currResult));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
currResult.add(nums[i]);
used[i] = true;
permuteRecur(nums, finalResult, currResult, used);
used[i] = false;
currResult.remove(currResult.size() - 1);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy