给定一个 没有重复 数字的序列,返回其所有可能的全排列。
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
let permute = nums => {
let ret = [];
if (nums === null || nums.length === 0) return ret;
let marked = Array(nums.length).fill(false);
let dfs = (nums, list) => {
if (list.length === nums.length) {
ret.push(list.slice())
return;
}
for (let i = 0; i < nums.length; i++) {
if (marked[i]) continue;
list.push(nums[i]);
marked[i] = true;
dfs(nums, list);
marked[i] = false;
list.pop();
}
}
dfs(nums, []);
return ret;
}
func permute(nums []int) [][]int {
var res [][]int
var dfs func(nums []int, list []int)
if len(nums) == 0 {
return res
}
marked := make([]bool, len(nums))
dfs = func(nums []int, list []int) {
if len(list) == len(nums) {
res = append(res, append([]int{}, list...))
return
}
for i := 0; i < len(nums); i++ {
if marked[i] {
continue
}
list = append(list, nums[i])
marked[i] = true
dfs(nums, list)
marked[i] = false
list = list[0:len(list) - 1]
}
}
dfs(nums, []int{})
return res
}
class Solution {
List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if (nums == null || nums.length == 0)
return ret;
dfs(nums, new boolean[nums.length], new ArrayList<Integer>());
return ret;
}
public void dfs(int[] nums, boolean[] marked, ArrayList<Integer> list){
if (list.size() == nums.length){
ret.add(new ArrayList(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if(marked[i])
continue;
list.add(nums[i]);
marked[i] = true;
dfs(nums, marked, list);
marked[i] = false;
list.remove(list.size() - 1);
}
}
}