C++中統計具有不同偶數的子集
給定一個正整數陣列。目標是找到陣列中數字的子集,使得每個子集都包含不同的偶數。所有具有相同元素的集合都計為1。[2,4,6]和[6,2,4]是同一個集合。
讓我們透過例子來理解
輸入 − arr[] = {1,3,5,7,8,3,2 };
輸出 − 具有不同偶數的子集數量為 − 3
解釋 − 子集將是 − [2], [8], [2,8]
輸入 − arr[] = {2,4,6 };
輸出 − 具有不同偶數的子集數量為 − 7
解釋 − 子集將是 − [2], [4], [6], [2,4], [2,6], [4,6], [2,4,6]
下面程式中使用的方法如下
我們建立一個數組中所有偶數的集合。這給出了不同偶數的個數。公式將是 2偶數個數 - 1
取一個數字陣列 arr[]。
函式 subset_even(int arr[], int size) 獲取一個數字陣列並返回具有不同偶數的子集。
將初始計數設為 0。
為偶數建立一個 unordered_set<int> un_set。
使用 for 迴圈遍歷 arr[]。從 i=0 到 i<length。
如果 arr[i]%2==0,則它是偶數。將其插入到 un_set 中。
取 count=un_set.size() // 不同的偶數。
更新 count=pow(2,count) - 1。
返回 count 作為結果。
示例
#include <bits/stdc++.h> using namespace std; int subset_even(int arr[], int size){ int count = 0; unordered_set<int> un_set; for(int i=0; i<size; i++){ if (arr[i] % 2 == 0){ un_set.insert(arr[i]); } } unordered_set<int>:: iterator i; count = un_set.size(); count = pow(2, count) - 1; return count; } int main(){ int arr[] = {10, 4, 21, 3, 5, 7, 6, 8}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of subsets having distinct even numbers are: "<<subset_even(arr, size); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count of subsets having distinct even numbers are: 15
廣告