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; 
    }
  • 相关阅读:
    C语言I博客作业10
    C言I博客作业09
    C言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言博客园作业05
    使用注解方式生成Hibernate映射文件
    技术英语单词中英文对照
    spring监听器
    Servlet
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/11213536.html
Copyright © 2011-2022 走看看