• 42. Subsets && Subsets II


    Subsets

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

    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]
    
    思想: 顺序读,取前面的每个子集,把该位置数放后面作为新的子集。
    class Solution {
    public:
        vector<vector<int> > subsets(vector<int> &S) {
            sort(S.begin(), S.end());
            vector<vector<int> > vec(1);
            for(size_t id = 0; id < S.size(); ++id) {
                int n = vec.size();
                while(n-- > 0) {
                    vec.push_back(vec[n]);
                    vec.back().push_back(S[id]);
                }
            }
            return vec;
        }
    };
    

    Subsets II

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

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    思想: 排序后,按照 1 的方法。但是若前面的数字与本数字相同,则只读取含有前面数字的每个子集,把自身放在后面作为一个新的子集。
    class Solution {
    public:
        vector<vector<int> > subsetsWithDup(vector<int> &S) {
            sort(S.begin(), S.end());
            vector<vector<int> > vec(1);
            size_t prePos, endTag;
            prePos = endTag = 0;
            for(size_t id = 0; id < S.size(); ++id) {
                if(id > 0 && S[id] != S[id-1]) endTag = 0;
                else endTag = prePos;
                size_t n = vec.size();
                prePos = n;
                while(n > endTag) {
                    --n;
                    vec.push_back(vec[n]);
                    vec.back().push_back(S[id]);
                }
            }
            return vec;
        }
    };
    
















              

  • 相关阅读:
    Javascript 闭包
    纯CSS实现侧边栏/分栏高度自动相等
    css实现16:9的图片比例
    CSS实现宽高成比例缩放
    div等比例缩放-------纯CSS实现自适应浏览器宽度的正方形
    websocket 实现简单网页版wechat
    Flask 简单使用,这一篇就够了!
    图灵机器人 V1 和 V2 接入方法
    Django中的cookie和session
    django 三件套(render,redirect,HttpResponse)
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3940198.html
Copyright © 2020-2023  润新知