LeetCode-Subsets II

来源:互联网 发布:linux mint 18.2 kde 编辑:程序博客网 时间:2024/05/17 20:26

题目:https://oj.leetcode.com/problems/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],  []]
分析:采用二进制法,使用Set去重

源码:Java版本
算法分析:二进制法,时间复杂度O(2^n),空间复杂度O(1)

public class Solution {    public List<List<Integer>> subsetsWithDup(int[] num) {        Arrays.sort(num);                  Set<List<Integer>> results = new HashSet<List<Integer>>();         List<List<Integer>> realResults = new ArrayList<List<Integer>>();                 int len=num.length;          for(int i=0;i<(1<<len);i++) {              List<Integer> path = new ArrayList<Integer>();              for(int j=0;j<len;j++) {                  if(((1<<j)&i)!=0) {                      path.add(num[j]);                  }              }              results.add(path);          }          realResults.addAll(results);        return realResults;      }    }

0 0
原创粉丝点击