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 }
  • 相关阅读:
    ajax与Servlet
    Myeclipse快捷键的设置以及默认的编码格式
    bootstrap02导航菜单
    bootstrap01登录小例子
    ajax
    面向对象04异常
    mysql
    Day10 Python基础之特殊函数(八)
    Day9 Python基础之函数基础(七)
    Day8 Python基础之遗漏知识点(六)
  • 原文地址:https://www.cnblogs.com/feiling/p/3256589.html
Copyright © 2011-2022 走看看