#Leetcode# 78. Subsets

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;
}

  

转载于:https://www.cnblogs.com/zlrrrr/p/9999290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值