题目
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]
]
解法思路(一)
- 排列组合的问题;
- 回溯法;
- 当给出输入的数组,代表整个排列组合的树就已经形成了,如下:

算法过程.png
- 问题转换成了,求这棵树中,所有从根节点到空节点的路径;
解法实现(一)
关键字
回溯
递归
树
树的路径
实现细节
- 由于树上每一层的边是有冲突的,上层的边用过的数字,下层的边就不能再用了,所以在回溯的过程中,要将边的状态置为可用;
- 已经确定的排列组合在往
res
中放的时候,要注意是深拷贝,否则递归过程中找到的组合保存不下来; - 用一个辅助数组
used
记录每个数字是否可选的状态;
package leetcode._46;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Solution46_1 {
private List<List<Integer>> res;
private boolean[] used;
public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
return res;
}
used = new boolean[nums.length];
LinkedList<Integer> combination = new LinkedList<>();
findCombination(nums, 0, combination);
return res;
}
private void findCombination(int[] nums, int index, LinkedList<Integer> combination) {
if (index == nums.length) {
res.add((List<Integer>)combination.clone());
return;
}
for (int i = 0; i < nums.length; i++) {
if (!used[i]) {
combination.addLast(nums[i]);
used[i] = true;
findCombination(nums, index + 1, combination);
combination.removeLast();
used[i] = false;
}
}
return;
}
}