在这个问题上,我们得到了N个元素的数组。并且需要返回的所有元素之和都可以被整数M整除。
Input : array = {4, 7, 3} ; M = 3
Output : 5+4+3 ; 5+4-3为了解决这个问题,我们需要了解幂集的概念,该幂集可用于查找所有可能的和。从该总和中,打印出所有可被M整除的值。
Step 1: Iterate overall combinations of ‘+’ and ‘-’ using power set. Step 2: If the sum combination is divisible by M, print them with signs.
#include <iostream>
using namespace std;
void printDivisibleSum(int a[], int n, int m){
for (int i = 0; i < (1 << n); i++) {
int sum = 0;
int num = 1 << (n - 1);
for (int j = 0; j < n; j++) {
if (i & num)
sum += a[j];
else
sum += (-1 * a[j]);
num = num >> 1;
}
if (sum % m == 0) {
num = 1 << (n - 1);
for (int j = 0; j < n; j++) {
if ((i & num))
cout << "+ " << a[j] << " ";
else
cout << "- " << a[j] << " ";
num = num >> 1;
}
cout << endl;
}
}
}
int main(){
int arr[] = {4,7,3};
int n = sizeof(arr) / sizeof(arr[0]);
int m = 3;
cout<<"The sum combination divisible by n :\n";
printDivisibleSum(arr, n, m);
return 0;
}输出结果
总和可以除以n-
- 4 + 7 - 3 - 4 + 7 + 3 + 4 - 7 - 3 + 4 - 7 + 3