zoukankan      html  css  js  c++  java
  • [leetcode]90. Subsets II数组子集(有重)

    Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

    Note: The solution set must not contain duplicate subsets.

    Input: [1,2,2]
    Output:
    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]

    题意:

    是的[leetcode]78. Subsets数组子集 follow up 

    这题强调给定数组可以有重复元素

    思路:

    需要先对给定数组排序,以便去重

    代码:

     1 class Solution {
     2     public List<List<Integer>> subsetsWithDup(int[] nums) {
     3         List<List<Integer>> result = new ArrayList<>();
     4         if(nums == null || nums.length ==0 )return result;
     5         Arrays.sort(nums);
     6         List<Integer> path = new ArrayList<>();
     7         dfs(0, nums, path, result);
     8         return result;    
     9     }
    10     
    11     private void dfs(int index, int[] nums, List<Integer> path, List<List<Integer>> result){
    12         result.add(new ArrayList<>(path));
    13         for(int i = index; i < nums.length; i++){
    14             if( i != index && nums[i] == nums[i-1] ) continue;
    15             path.add(nums[i]);
    16             dfs(i + 1, nums, path, result);
    17             path.remove(path.size() - 1);
    18         }
    19     }
    20 }
  • 相关阅读:
    C语言II作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言I博客作业12—学期总结
    第一次作业
    C语言I博客作业02
    C语言I博客作业11
    C语言||作业01
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9191503.html
Copyright © 2011-2022 走看看