C++ 中满足给定条件的子集计数
给定一个数字数组和一个整数 x 作为输入。目标是找到 arr[] 的所有子集,使得该集合的各个元素以及它们的和都能被 x 整除。
例如
输入
arr[] = {1,2,3,4,5,6} x=3输出
Count of subsets that satisfy the given condition :3
解释
The subsets will be: [3], [6], [3,6]
输入
arr[] = {1,2,3,4,5,6} x=4输出
Count of subsets that satisfy the given condition :1
解释
The subsets will be: [4]
**下面程序中使用的方案如下** −
在这种方法中,我们将计算 arr[] 中能被 x 整除的元素的数量,然后返回 2count−1 作为所需的子集数量。
取一个整数数组 arr[]。
取 x 作为输入。
函数 count(int arr[], int n, int x) 获取一个数组和 x 并返回满足给定条件的子集的数量。
如果 x 为 1,则它能整除所有元素,因此返回
示例
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int sub_sets(int arr[], int size, int val){
int count = 0;
if (val == 1){
count = pow(2, size) − 1;
return count;
}
for (int i = 0; i < size; i++){
if (arr[i] % val == 0){
count++;
}
}
count = pow(2, count) − 1;
return count;
}
int main(){
int arr[] = { 4, 6, 1, 3, 8, 10, 12 }, val = 4;
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of sub−sets that satisfy the given condition are: "<<sub_sets(arr, size, val);
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Count of sub−sets that satisfy the given condition are: 7
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP