我注意到很多的回溯问题有解决的方法有两种。两种方法来打印所有排列 - 返回与穿过“结果”列表
一个是返回“无论是必需的名单”,VS,贯穿每个呼叫的“结果”,并追加到它。 返回的缺点是什么?(它是更少的内存/时间效率)? 示例:要打印所有可能的排列,与第二个排序相比,这种解决方案的效率如何? 对不起,如果这不是合适的论坛问这个问题,我找不到更好的地方。
public List<List<Integer>> perm(int[] nums){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(nums.length == 0){
result.add(new ArrayList<Integer>());
return result;
}
for(int i= 0;i<nums.length;i++){
int first = nums[i];
int[] remnums = new int[nums.length-1];
int j = 0;
for(int cur : nums){
if(cur != first){
remnums[j] = cur;j++;
}
}
List<List<Integer>> tmp = perm(remnums);
for(List<Integer> t : tmp){
t.add(0,first);
}
result.addAll(tmp);
}
return result;
}
第二个办法---
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
// Arrays.sort(nums); // not necessary
backtrack(list, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
} else{
for(int i = 0; i < nums.length; i++){
if(tempList.contains(nums[i])) continue; // element already exists, skip
tempList.add(nums[i]);
backtrack(list, tempList, nums);
tempList.remove(tempList.size() - 1);
}
}
}
https://codereview.stackexchange.com? – nullpointer
ok.what about cs.stackexchange.com? – code4fun
最好codereview。 – nullpointer