全排列
题目描述
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解题思路
个人AC
没有思路QAQ。
最优解
回溯算法是一种尝试探索所有可能的候选解来找出所有解的算法。如果候选解被确认“不是一个解(或至少不是最后一个解)”,就回溯到上一个“回溯点”进行一些变化后再次尝试。

class Solution {
public List<List<Integer>> permute(int[] nums) {
// construct output list
List<List<Integer>> output = new ArrayList<>();
// convert nums into list since output is a list of lists
List<Integer> sequence = new ArrayList() {{
for (int num : nums) {
this.add(num);
}
}};
int n = nums.length;
backtrack(output, sequence, n, 0);
return output;
}
private void backtrack(List<List<Integer>> output, List<Integer> sequence, int n, int first) {
// if all integers are used up
if (first == n - 1) {
output.add(new ArrayList<>(sequence));
return;
}
for (int i = first; i < n; i++) {
// place i-th integer first in the current permutation
Collections.swap(sequence, first, i);
permute(output, sequence, n, first + 1);
// backtrack
Collections.swap(sequence, first, i);
}
}
}
时间复杂度: O ( A n n ) O(A^{n}_{n}) O(Ann);
空间复杂度: O ( n A n n ) O(nA^{n}_{n}) O(nAnn)。

本文深入解析了全排列问题,提供了一种使用回溯算法解决该问题的最优解方案。通过实例展示,详细解释了如何利用回溯算法生成给定序列的所有可能全排列,包括具体实现代码及时间、空间复杂度分析。
1592

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



