输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
定义递归函数,dfs(depth, tmp, used)
递归结束条件为填完n个位置
时间复杂度O(\(n \times n!\)),n为序列长度
空间复杂度O(n)
class Solution {
public List<List<Integer>> permute(int[] nums) {
// 结果列表
List<List<Integer>> ans = new ArrayList<>();
int len = nums.length;
if (len == 0) return ans;
// 初始化当前排列
List<Integer> tmp = new ArrayList<>();
// 标记数组
boolean[] used = new boolean[len];
dfs(nums, ans, len, 0, tmp, used);
return ans;
}
/**
* @param nums 目标数组
* @param ans 最终结果列表
* @param len 数组长度
* @param depth 当前递归深度
* @param tmp 当前排列
* @param used 标记数组
*/
private void dfs(int[] nums, List<List<Integer>> ans, int len, int depth, List<Integer> tmp, boolean[] used) {
// 递归结束条件未递归深度等于数组长度
if (depth == len) {
ans.add(new ArrayList<>(tmp));
return;
}
for (int i = 0; i < len; i++) {
// 当前数字已被使用
if (used[i]) continue;
// 当前数字未被使用
tmp.add(nums[i]);
used[i] = true;
// 进行下一层递归
dfs(nums, ans, len, depth + 1, tmp, used);
// 回溯
tmp.remove(tmp.size() - 1);
used[i] = false;
}
}
}
//class Test{
// public static void main(String[] args) {
// Solution test = new Solution();
// int[] nums = {1,2,3};
// System.out.println(test.permute(nums));
// }
//}
原文:https://www.cnblogs.com/lijiong/p/14419544.html