zoukankan      html  css  js  c++  java
  • Subsets,Subsets II

    一.Subsets

    Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]
    class Solution {
    public:
        void dfs(vector<int>& nums ,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
        {
            for(int i=startPos;i<numsSize;i++){
                oneOfRes.push_back(nums[i]);
                res.push_back(oneOfRes);
                dfs(nums,numsSize,i+1,res,oneOfRes);
                oneOfRes.pop_back();
            }
        }
        vector<vector<int>> subsets(vector<int>& nums) {
            sort(nums.begin(),nums.end());
            vector<vector<int>> res;
            vector<int> oneOfRes;
            res.push_back(vector<int>());
            int numsSize = nums.size();
            dfs(nums,numsSize,0,res,oneOfRes);
            return res;
        }
    };

     二.SubsetsII

    Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    class Solution {
    public:
        void dfs(vector<int>& nums,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
        {
            for(int i=startPos;i<numsSize;i++){
                if(i>startPos && nums[i]==nums[i-1]){
                    continue;
                }
                oneOfRes.push_back(nums[i]);
                res.push_back(oneOfRes);
                dfs(nums,numsSize,i+1,res,oneOfRes);
                oneOfRes.pop_back();
            }
        }
        vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            sort(nums.begin(),nums.end());
            vector<vector<int>> res;
            vector<int> oneOfRes;
            int numsSize = nums.size();
            res.push_back(oneOfRes);
            dfs(nums,numsSize,0,res,oneOfRes);
            return res;
        }
    };
  • 相关阅读:
    7503E-M-irf2配置以及bfd配置
    nltk_29_pickle保存和导入分类器
    nltk_28Twitter情感分析模型
    美国在研新药_读取单个PDF
    Python:eval的妙用和滥用
    opencv_判断两张图片是否相同
    Make 命令教程
    pdf在线处理网站
    K-Means clusternig example with Python and Scikit-learn(推荐)
    自然语言27_Converting words to Features with NLTK
  • 原文地址:https://www.cnblogs.com/zengzy/p/5024597.html
Copyright © 2011-2022 走看看