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 }
  • 相关阅读:
    python3中,os.path模块下常用的用法总结
    python 中str format 格式化数字补0方法
    5分钟让你明白“软链接”和“硬链接”的区别
    获得Python脚本所在目录
    sshd超时
    pip 指定源安装
    python编程规范
    Git冲突解决
    Git冲突解决
    git 更新某个目录或文件
  • 原文地址:https://www.cnblogs.com/feiling/p/3256589.html
Copyright © 2011-2022 走看看