当前位置:网站首页>Subsets of leetcode topic resolution

Subsets of leetcode topic resolution

2022-06-23 08:39:00 ruochen

Given a set of distinct integers, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,

If nums = 1,2,3, a solution is:

[

3,

1,

2,

1,2,3,

1,3,

2,3,

1,2,

[]

]

    int target;//  frequency 
    Integer[] stack;//  Store every spread 
    List<List<Integer>> rt;//  Store results 
    public void search(int p, int[] nums) {
        //  If the length is k, be stack Is one of the results , Save results 
        if (p == target) {
            rt.add(new ArrayList<Integer>(Arrays.asList(stack)));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (p > 0 && nums[i] <= stack[p - 1]) {
                continue;
            }
            stack[p] = nums[i];
            search(p + 1, nums);
        }
    }
    public List<List<Integer>> subsets(int[] nums) {
        Arrays.sort(nums);
        rt = new ArrayList<List<Integer>>();
        //  Do it separately 0~num.length Combination of lengths 
        for (int i = 0; i <= nums.length; i++) {
            target = i;
            stack = new Integer[i];
            search(0, nums);
        }
        return rt;
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201102041064250.html