8.1—暴力枚举法—Subsets

来源:互联网 发布:激光洗眉机网络假货 编辑:程序博客网 时间:2024/05/29 10:33
描述
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],
[]
]

#include<iostream>#include<algorithm>#include<vector>using namespace std;vector<vector<int>> Subsets(vector<int> data){vector<vector<int>> result;if (data.size() <= 0)return result;int length = data.size();int num = pow(2, length);int num1 = pow(2, length - 1);sort(data.begin(), data.end());for (int i = 0; i < num; i++){vector<int> path;if (i == 0){result.push_back(path);continue;}for (int j = 0; j < length;j++){int temp = num1;temp = temp >>= j;if (i&temp){path.push_back(data[j]);}}result.push_back(path);}return result;}int main(){int a[4] = { 1, 8,2, 3 };vector<int> data(begin(a), end(a));vector<vector<int>> res = Subsets(data);for (int i = 0; i < res.size(); i++){if (res[i].size() == 0)cout << "[]";for (int j = 0; j < res[i].size(); j++)cout << res[i][j] << " ";cout << endl;}}

原创粉丝点击