给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
Ref Link:https://leetcode.cn/problems/permutations/
Difficulty:Medium
Tag:Array,Back Tracking
Updated Date:2023-09-20
示例1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:
输入:nums = [1]
输出:[[1]]
1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums 中的所有整数 互不相同
class Solution {
public List> permute1(int[] nums) {
return permuteRecursive(nums, nums.length);
}
public List> permuteRecursive(int[] nums, int length) {
if (length == 1) {
List> result = new ArrayList<>();
LinkedList start = new LinkedList<>();
start.add(nums[0]);
result.add(start);
return result;
} else {
return merge(permuteRecursive(nums, length - 1), nums[length - 1]);
}
}
public List> merge(List> list, Integer one) {
List> result = new ArrayList<>();
for (List item : list) {
for (int i = 0; i <= item.size(); i++) {
result.add(insert(item, one, i));
}
}
return result;
}
LinkedList insert(List list, Integer one, int index) {
LinkedList newList = new LinkedList<>();
newList.addAll(list);
newList.add(index, one);
return newList;
}
}
26/26 cases passed (1 ms)
Your runtime beats 77.93 % of java submissions
Your memory usage beats 29.85 % of java submissions (42.7 MB)
回溯算法
排列问题需要一个used数组,标记已经选择的元素,一个排列里一个元素只能使用一次
递归终止条件:当收集元素的数组path的大小达到和nums数组一样大的时候,说明找到了一个全排列,此时要收集结果。
排列问题是回溯算法解决的经典题目,排列问题和组合问题的不同点: 每层都是从0开始搜索而不是startIndex ; 需要used数组记录path里都放了哪些元素了
public List> permute(int[] nums) {
List> result = new ArrayList>();
if (nums == null || nums.length == 0)
return result;
boolean[] used = new boolean[nums.length];
subPermute(nums, used, result, new ArrayList<>());
return result;
}
public void subPermute(int[] nums, boolean[] used, List> result, List path) {
if(path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i=0; i
26/26 cases passed (1 ms)
Your runtime beats 77.93 % of java submissions
Your memory usage beats 92.98 % of java submissions (42.3 MB)