Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution:
全排列。
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) {
return res;
}
PermutationHelp(nums, 0, res);
return res;
}
private void PermutationHelp(int[] nums, int i, List<List<Integer>> res) {
if(i == nums.length-1) {
List<Integer> list = new ArrayList<>();
for(int c = 0; c < nums.length; c ++) {
list.add(nums[c]);
}
res.add(list);
}else {
Set<Integer> set = new HashSet<Integer>();
for(int j = i;j < nums.length;j ++) {
if(j == i || !set.contains(nums[j])) {
set.add(nums[i]);
swap(nums, i, j);
PermutationHelp(nums, i+1, res);
swap(nums, j, i);
}
}
}
}
public void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
本文深入解析了全排列算法,提供了一种基于递归的解决方案,通过交换元素位置来生成所有可能的排列组合,适用于给定的整数集合。示例中使用了[1,2,3]作为输入,展示了算法的具体实现和输出结果。
1718

被折叠的 条评论
为什么被折叠?



