通过在 C++ 中更改符号来打印 N 个元素的所有组合,以便其和可以被 M 整除
在此问题中,我们给出 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
广告
数据结构
网络
RDBMS
操作系统
爪哇语
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP