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; 
    }
  • 相关阅读:
    命名规则
    数据库的基本概念(三大范式,数据)
    集合的排序
    装箱拆箱
    异常处理
    单行函数
    表管理
    创建表,插入列....
    PL/SQL 块
    单行函数的案例
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11213536.html
Copyright © 2011-2022 走看看