zoukankan      html  css  js  c++  java
  • Subsets II

    Given a collection of integers that might contain duplicates, nums, return all possible subsets.

    Note: The solution set must not contain duplicate subsets.

    For example,
    If nums = [1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    

    分析: 因为有重复的元素,重新模拟组合的情况,首先对于任何结果都含有{}, 然后加入第一个元素1,结果变为{{},{1}}, ,再加入第二个元素2,对原有结果中的两个分别添加进入,{{},{1},{2},{1,2}},再加入2只能为{{},{1},{2},{1,2},{2,2},{1,2,2}} 即第一次加2 添加了两个新组合{2},{1,2} 第二次添加的新组合为{2,2},{1,2,2} 这么看重复的时候就不要重新读取原有结果中的所有元素,在前一个里面直接加好了

    class Solution {
    public:
        int findlen(int value, int i, const vector<int> & nums ){
            int len=1;
            for(int j=i+1; j<nums.size()&&(nums[j]==value); j++) len++;
            return len;
            
        }
        vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            vector<vector<int>> res;
            vector<int> empty;
            res.push_back(empty);
            sort(nums.begin(),nums.end());
            for(int i=0; i<nums.size(); ){
                int value = nums[i];
                int len =1;
                cout <<"i = "<< i <<endl;
                len = findlen(value,i,nums);
                cout << len<<endl;
                int m =res.size();
                for(int t=0; t<m; t++){
                    vector<int> temp=res[t];
                    for(int j=0; j<len; j++){
                        temp.push_back(value);
                        res.push_back(temp);
                    }
                }
                i+=len;
               
            }
            return res;
        }
        
      
    };
  • 相关阅读:
    html-----018----HTML Web Server/HTML URL 字符编码
    html-----017
    SQL Server 2008 R2评估期已过的解决办法和sqlserver 服务器打不开问题
    Eclipse快捷键大全
    with递归
    PIVOT使用
    SSH框架搭建
    更换开发环境后设置Tomcat和jdk版本
    MyBatis 一对多和多对一关联查询
    MyBatis 使用接口增删改查和两表一对一级联查询
  • 原文地址:https://www.cnblogs.com/willwu/p/6254057.html
Copyright © 2011-2022 走看看