leetcode:Subsets II

来源:互联网 发布:电魂网络招聘 编辑:程序博客网 时间:2024/05/19 02:25

给出一个集合,返回他的所有子集合

直接DFS,然后再进行判重


<span style="font-size:18px;">public class Solution {    static List<List<Integer>> ans = new ArrayList<>();    static ArrayList<Integer> stack = new ArrayList<>();    static int dept ;    static int[] a;    public List<List<Integer>> subsetsWithDup(int[] num) {        ans.clear();        stack.clear();        dept = num.length;        a = num;        Arrays.sort(a);        dfs(0);                return ans;    }        public static void dfs(int cur){        if(cur == dept){            ArrayList<Integer> t = new ArrayList<>();            for(int i = 0; i < stack.size(); ++i){                t.add(stack.get(i));            }            for(int i = 0; i < ans.size(); ++i){                if(ans.get(i).equals(t)){                    return ;                }            }            ans.add(t);        }        else{            dfs(cur + 1);            stack.add(a[cur]);            dfs(cur + 1);            stack.remove(stack.size() - 1);        }    }}</span>






0 0
原创粉丝点击