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-java17 Show documentation
Show all versions of leetcode-in-java17 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
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 #2022_06_16_Time_1_ms_(97.24%)_Space_42.2_MB_(96.25%)
import java.util.ArrayList;
import java.util.List;
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);
}
}
}