Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
,[3,1,2]
, and[3,2,1]
.
思路:经典的backtracking. 不要记代码,弄清楚原理,传递到下一层的是什么信息,然后
choosen
explore
unchoosen
要记录choosen的状态,所以要传递一个visited boolean array;
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<>();
int n = nums.length;
boolean[] visited = new boolean[n];
dfs(lists, list, nums, visited);
return lists;
}
private void dfs(List<List<Integer>> lists, List<Integer> list, int[] nums, boolean[] visited) {
if(list.size() == nums.length) {
lists.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++) {
if(!visited[i]) {
list.add(nums[i]);
visited[i] = true;
dfs(lists, list, nums, visited);
visited[i] = false;
list.remove(list.size() - 1);
}
}
}
}