leetcodeの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
=
, a solution is:
解决の考え方:もしS={1,2,3}ならば、行列(8*3)をリストして、全配列をリストして、各行とその他の行がすべて异なる配列であることを保证して、このように私达は各列の数字の出现の规则を発见します.例えば、第1列は、1 1 1 1 1、4つの空を並べます.2番目の列は、2つの2、2つの空、2つの2、2つの空を並べます.3番目の列は、1つの3、1つの空、1つの3、1つの空を並べます...我々の目標は,この行列を埋め込み,各行が一意のsubsetであることを保証することである.アルゴリズムの時間的複雑度はS.size()*power(2,S.size()−1)である.
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],
[]
]
解决の考え方:もしS={1,2,3}ならば、行列(8*3)をリストして、全配列をリストして、各行とその他の行がすべて异なる配列であることを保证して、このように私达は各列の数字の出现の规则を発见します.例えば、第1列は、1 1 1 1 1、4つの空を並べます.2番目の列は、2つの2、2つの空、2つの2、2つの空を並べます.3番目の列は、1つの3、1つの空、1つの3、1つの空を並べます...我々の目標は,この行列を埋め込み,各行が一意のsubsetであることを保証することである.アルゴリズムの時間的複雑度はS.size()*power(2,S.size()−1)である.
#include <math.h>
#include <stdio.h>
bool comparator (int i,int j) { return (i<j); }
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
std::sort (S.begin(), S.end(), comparator);
if(S.size() == 0){
vector<vector<int> > result(0, vector<int>(0));
return result;
}
vector<vector<int> > result(pow(2, S.size()), vector<int>(0));
int n = S.size();
for(int i = 0; i < n; i++)
{
//how many cycle.
for (int j = 0; j < pow(2, n) - 1; j+= pow(2, n-i))
{
//half needs to push.
for( int k = 0; k < pow(2, n - i - 1) ; k ++ )
{
result[j + k].push_back(S[i]);
}
}
}
return result;
}
};