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