def permute(nums):
res=[]
def bt(path,used):
if len(path)==len(nums): res.append(path[:]); return
for i in range(len(nums)):
if used[i]: continue
used[i]=True; path.append(nums[i])
bt(path,used)
used[i]=False; path.pop()
bt([],[False]*len(nums))
return res
public List<List<Integer>> permute(int[] nums){
List<List<Integer>> res=new ArrayList<>();
backtrack(res,new ArrayList<>(),nums,new boolean[nums.length]);
return res;
}
void backtrack(List<List<Integer>> res,List<Integer> path,int[] nums,boolean[] used){
if(path.size()==nums.length){res.add(new ArrayList<>(path));return;}
for(int i=0;i<nums.length;i++){
if(used[i]) continue;
used[i]=true; path.add(nums[i]);
backtrack(res,path,nums,used);
used[i]=false; path.remove(path.size()-1);
}
}
Backtracking template. Python nested function vs Java parameters.
def permute(nums):
res=[]
def bt(path,used):
if len(path)==len(nums): res.append(path[:]); return
for i in range(len(nums)):
if used[i]: continue
used[i]=True; path.append(nums[i])
bt(path,used)
used[i]=False; path.pop()
bt([],[False]*len(nums))
return res
public List<List<Integer>> permute(int[] nums){
List<List<Integer>> res=new ArrayList<>();
backtrack(res,new ArrayList<>(),nums,new boolean[nums.length]);
return res;
}
void backtrack(List<List<Integer>> res,List<Integer> path,int[] nums,boolean[] used){
if(path.size()==nums.length){res.add(new ArrayList<>(path));return;}
for(int i=0;i<nums.length;i++){
if(used[i]) continue;
used[i]=true; path.add(nums[i]);
backtrack(res,path,nums,used);
used[i]=false; path.remove(path.size()-1);
}
}
1. Choose element 2. Mark used 3. Recurse 4. Unchoose