Permutations
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
][1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
dfs(nums, res, 0);
return res;
}
private void dfs(int[] nums, List<List<Integer>> res, int pos) {
if (pos == nums.length) { // 所有位都已经确定
List<Integer> lst = new ArrayList<>();
for (int num : nums) lst.add(num);
res.add(lst);
return;
}
// 循环考虑每个候选数字,将其换到当前pos之后继续向后递归
for (int i = pos; i < nums.length; ++i) {
swap(nums, pos, i);
dfs(nums, res, pos + 1);
swap(nums, pos, i); // backtracking
}
}
private void swap(int[] nums, int a, int b) {
int t = nums[a];
nums[a] = nums[b];
nums[b] = t;
}
}举例说明,如果input array 为 [1,2,3]
我们先生成: res = [[1], [2], [3]]
然后将其中每个list拿出来,在其后append上下一个没有重复过的数字,再放回res,
我们得到:res = [[1,2], [1,3], [2,1], [2,3], [3,1], [3,2]]
重复上面步骤,直到res中每个list的长度等于nums.length, 我们就结束。class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length == 0) return res;
res.add(new ArrayList<>());
for (int i = 0; i < nums.length; ++i) {
List<List<Integer>> newRes = new ArrayList<>();
for (List<Integer> path : res) {
for (int num : nums) {
if (! path.contains(num)) {
List<Integer> newPath = new ArrayList<>(path);
newPath.add(num);
newRes.add(newPath);
}
}
}
res = newRes;
}
return res;
}
}