每个槽位可以选什么数字, dfs, 记录哪个数字用过了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
/**
* 每个槽位可以选什么数字, dfs, 记录哪个数字用过了
*/
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
List<List<Integer>> ans = new ArrayList<>();
List<Integer> permutation = Arrays.asList(new Integer[n]);;
dfs(0, nums, permutation, new boolean[n], ans);
return ans;
}

private void dfs(int i, int[] nums, List<Integer> permutation, boolean[] visited, List<List<Integer>> ans) {
if (i == nums.length) {
ans.add(new ArrayList<>(permutation));
return ;
}
for (int j = 0; j < nums.length; j++) {
if (visited[j])
continue;

permutation.set(i, nums[j]);
visited[j] = true;
dfs(i+1, nums, permutation, visited, ans);
visited[j] = false;
}
}
}

Comments
Recent Posts
Untitled
Categories
Tags
Website Info
Article Count :
2
Total Word Count :
1.6k
Unique Visitors :
Page Views :
Last Update :