/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {
// write your code here
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(nums == null || nums.size() == 0)
return res;
boolean[] visited = new boolean[nums.size()];
ArrayList<Integer> tmp = new ArrayList<Integer>();
dfs(res,visited, tmp, nums);
return res;
}
public void dfs(ArrayList<ArrayList<Integer>> res, boolean[] visited, ArrayList<Integer> tmp, ArrayList<Integer> nums) {
if(tmp.size() == nums.size()){
res.add(new ArrayList<Integer>(tmp));
return;
}
for(int i = 0 ; i < nums.size(); i++) {
if(!visited[i]){
visited[i] = true;
tmp.add(nums.get(i));
dfs(res, visited,tmp,nums);
visited[i] = false;
tmp.remove(tmp.size()-1);
}
}
}
Leave A Comment