zoukankan      html  css  js  c++  java
  • leetcode -- Subsets II

    Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    [解题思路]
    本题与Subsets唯一区别在于输入会有重复元素,这是面试时需要注意的,尽可能考虑所有输入情况
    代码与上一题只在25-27有区别,当发现重复元素时则跳过


     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         Arrays.sort(num);
     6         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     7         ArrayList<Integer> output = new ArrayList<Integer>();
     8         generate(result, output, 0, num, num.length);
     9         return result;
    10     }
    11     
    12      public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> output,
    13                     int depth, int[] S, int len){
    14         result.add(output);
    15         if(depth == len){
    16             return;
    17         }
    18         
    19         for(int i = depth; i < len; i++){
    20             ArrayList<Integer> tmp = new ArrayList<Integer>();
    21             tmp.addAll(output);
    22             tmp.add(S[i]);
    23             generate(result, tmp, i + 1, S, len);
    24             
    25             while(i + 1 < len && S[i] == S[i+1]){
    26                 i++;
    27             }
    28         }
    29     }
    30 }
  • 相关阅读:
    判断一个值是不是数字
    webpack起的项目怎么用手机访问?
    vue 父子组件数据双向绑定
    js取整
    封装加减乘除函数 解决JS 浮点数计算 Bug
    javascript笔记 (持续更新)
    ajax请求的原生js实现
    程序员の健康和效率装备列表,普通人也能参考
    Java static,final 基本概念
    Download EditPlus Text Editor
  • 原文地址:https://www.cnblogs.com/feiling/p/3256589.html
Copyright © 2011-2022 走看看