zoukankan      html  css  js  c++  java
  • 90. Subsets II (Java)

    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.

    Example:

    Input: [1,2,2]
    Output:
    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    
     
    class Solution {
        public List<List<Integer>> subsetsWithDup(int[] nums) {
            result = new ArrayList<>();
            List<Integer> ans = new ArrayList<Integer>();
            Arrays.sort(nums); //nums可能是乱序的,要先排序
            backtrack(ans, nums, 0);
            return result;
        }
        
        public void backtrack(List<Integer> ans, int[] nums, int depth){
            if(depth >= nums.length) {
                List<Integer> new_ans = new ArrayList<Integer>(ans);
                result.add(new_ans);
                return;
            }
              
            int i = depth+1;
            while(i < nums.length){
                if(nums[depth] == nums[i]) i++;
                else break;
            }
            
            int j = depth;
            backtrack(ans, nums, i); //not add
            while(j < i){
                ans.add(nums[depth]);
                backtrack(ans, nums, i);
                j++;
            }
            
            //reset
            while(j > depth){
                ans.remove(ans.size()-1);
                j--;
            }  
        }
        
        private List<List<Integer>> result; 
    }
  • 相关阅读:
    正则表达式口诀
    Ajax请求的四种方式
    jQuery插件 -- jQuery UI插件
    电脑操作技巧
    递归
    声纹识别环境初次搭建
    视频编码book_实战_全角度——1
    SDK等阅读笔记
    音视频bug调试
    音视频开发进阶指南(二)
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11213536.html
Copyright © 2011-2022 走看看