Subset求数组的所有子集

Subset求数组的所有子集

Description

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],
[]
]

方法1

1.基于DFS的递归

原数组中每一个元素在子集中有两种状态:要么存在、要么不存在。这样构造子集的过程中每个元素就有两种选择方法:选择、不选择,因此可以构造一颗二叉树来表示所有的选择状态:二叉树中的第i+1层第0层无节点表示子集中加入或不加入第i个元素,左子树表示加入,右子树表示不加入。所有叶节点即为所求子集。因此可以采用DFS的递归思想求得所有叶节点。

//S为原数组,temp为当前子集,level为原数组中的元素下标亦为二叉树的层数,result为所求子集集合
void subsets(vector<int> &S,vector<int> temp,int level,vector<vector<int> > &result)
  {
    //如果是叶子节点则加入到result中
    if(level == S.size())
    {
      result.push_back(temp);
      return;
    }
    //对于非叶子节点,不将当前元素加入到temp中
    subsets(S,temp,level + 1,result);
    //将元素加入到temp中
    temp.push_back(S[level]);
    subsets(S,temp,level + 1,result);
  }

方法2

基于同质的递归
只要我们能找到比原问题规模小却同质的问题,都可以用递归解决。比如要求{1, 2, 3}的所有子集,可以先求{2, 3}的所有子集,{2, 3}的子集同时也是{1, 2, 3} 的子集,然后我们把{2, 3}的所有子集都加上元素1后(注意排序),又得到同样数量的子集, 它们也是{1, 2, 3}的子集。这样一来,我们就可以通过求{2, 3}的所有子集来求 {1, 2, 3}的所有子集了。即为求1,2,3的子集,要先求2,3的子集,然后再把1加入到2,3的子集中去,典型的递归思路。代码如下:

vector<vector<int> > subsets(vector<int> &S,int idx,int n)
  {
    vector<vector<int> > result;
    if(idx == n)
    {
      vector<int> temp;
      result.push_back(temp);
    }
    else
    {
      vector<vector<int> > vec = subsets(S,idx + 1,n);
      int a = S[idx];
      for(int i = 0; i < vec.size();i++)
      {
        vector<int> v = vec[i];
        result.push_back(v);
        v.push_back(a);
        sort(v.begin(),v.end());
        result.push_back(v);
      }
    }
    return result;
  }

方法3

位运算
求子集问题就是求组合问题。数组中的n个数可以用n个二进制位表示,当某一位为1表示选择对应的数,为0表示不选择对应的数。

vector<vector<int> > subsets(vector<int> &S,int n)
  {
     //n个数有0~max-1即2^n中组合,1<<n表示2^n
    int max = 1<<n;
    vector<vector<int> >result;
    for(int i = 0;i < max;i++)
    {
      vector<int> temp;
      int idx = 0;
      int j = i;
      while(j > 0)
      {
        //判断最后一位是否为1,若为1则将对应数加入到当前组合中
        if(j&1)
        {
          temp.push_back(S[idx]);
        }
        idx++;
        //判断了这一位是否为1后要右移
        j = j>>1;
      }
      //判断完了一种组合,加入到结果集中
      result.push_back(temp);
    }
    return result;
  }

猜你喜欢

转载自blog.csdn.net/lvquanye9483/article/details/81567974