https://leetcode.com/problems/subsets/
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
题解:状压 一共有 $1 << n$ 个子集 包括空集 所以 $i$ 从 $0$ 到 $(1 << n) - 1$ 将 $i$ 转化为二进制 出现 $1$ 的位置对应的数组里的数字输出 否则不输出 写出来的第一道状压的题目!!!
代码1:
(!这个不是 AC 代码!并没有适应 Leetcode 的格式 )
#include <bits/stdc++.h>
using namespace std;
int n;
int num[1010];
int bin[1010];
int cnt = 0;
void A(int x) {
while(x) {
bin[cnt ++] = x % 2;
x /= 2;
}
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i ++)
scanf("%d", &num[i]);
for(int i = 0; i < (1 << n); i ++) {
cnt = 0;
A(i);
for(int j = 0; j < cnt; j ++) {
if(bin[j])
printf("%d ", num[j]);
}
printf("\n");
}
return 0;
}