最近做了几道题都和“回溯”有关,也见怪不怪了。
推荐一个作者的详解:作者:liweiwei1419
链接:https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
截了一个图过来:

个人微改:
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class Permutations_2 {
public static void main(String args[]) {
int a[] = new int[] {1,1,2};
List<List<Integer>> hah = permutation(a);
System.out.println(hah);
}
static List<List<Integer>> permutation(int nums[]){
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
if(len==0) {
return res;
}
Arrays.sort(nums);
boolean used[] = new boolean[len];
Deque<Integer> path = new ArrayDeque<>(len);
dfs(nums,len,0,used,path,res);
return res;
}
static void dfs(int nums[],int len,int depth,boolean[] used,Deque<Integer> path,List<List<Integer>> res) {
if(depth==len) {
res.add(new ArrayList<>(path));
return;
}
for(int i=0;i<len;i++) {
if(used[i]) {
continue;
}
if(i>0 && nums[i]==nums[i-1] && !used[i-1]) {
continue;
}
path.addLast(nums[i]);
used[i]=true;
dfs(nums,len,depth+1,used,path,res);
used[i]=false;
path.removeLast();
}
}
}

本文介绍了如何使用Java实现回溯法来解决LeetCode中的排列组合问题。作者提供了详细的代码实现,包括一个核心的深度优先搜索(DFS)函数,用于找到所有不重复的排列。代码中特别处理了数组中有重复元素的情况,避免生成重复的解。此外,还展示了如何使用Deque作为路径存储结构以及如何维护一个布尔数组记录元素是否被使用过。
4782

被折叠的 条评论
为什么被折叠?



