透過在 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
廣告