📌  相关文章
📜  通过更改符号来打印N个元素的所有组合,以使它们的和可被M整除

📅  最后修改于: 2021-06-25 17:47:56             🧑  作者: Mango

给定一个由N个整数和一个整数M组成的数组。您可以更改数组中任何元素的符号(正号或负号)。任务是打印数组元素的所有可能组合,这些组合可以通过更改元素的符号来获得,以使它们的和可被M整除。

注意:您必须采用每种组合中的所有数组元素,并以与数组中存在的元素相同的顺序。但是,您可以更改元素的符号。

例子:

方法:此处使用功率设置的概念来解决此问题。使用功率集生成可以应用于元素数组的所有可能的符号组合。如果获得的总和可被M整除,则打印该组合。步骤如下:

  • 使用幂集迭代“ +”和“-”的所有可能组合。
  • 迭代数组元素,如果设置了从左数第j个位,则假定该数组元素为正;如果未设置该位,则假定该数组元素为负。请参考此处检查是否设置了任何索引。
  • 如果总和可被M整除,则再次遍历数组元素,并将它们与sign(’+’或’-‘)一起打印。

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to print all the combinations
void printCombinations(int a[], int n, int m)
{
 
    // Iterate for all combinations
    for (int i = 0; i < (1 << n); i++) {
        int sum = 0;
 
        // Initially 100 in binary if n is 3
        // as 1<<(3-1) = 100 in binary
        int num = 1 << (n - 1);
 
        // Iterate in the array and assign signs
        // to the array elements
        for (int j = 0; j < n; j++) {
 
            // If the j-th bit from left is set
            // take '+' sign
            if (i & num)
                sum += a[j];
            else
                sum += (-1 * a[j]);
 
            // Right shift to check if
            // jth bit is set or not
            num = num >> 1;
        }
 
        if (sum % m == 0) {
 
            // re-initialize
            num = 1 << (n - 1);
 
            // Iterate in the array elements
            for (int j = 0; j < n; j++) {
 
                // If the jth from left is set
                if ((i & num))
                    cout << "+" << a[j] << " ";
                else
                    cout << "-" << a[j] << " ";
 
                // right shift
                num = num >> 1;
            }
            cout << endl;
        }
    }
}
 
// Driver Code
int main()
{
    int a[] = { 3, 5, 6, 8 };
    int n = sizeof(a) / sizeof(a[0]);
    int m = 5;
 
    printCombinations(a, n, m);
    return 0;
}


Java
import java.io.*;
 
class GFG
{
     
// Function to print
// all the combinations
static void printCombinations(int a[],
                              int n, int m)
{
 
    // Iterate for all
    // combinations
    for (int i = 0;
             i < (1 << n); i++)
    {
        int sum = 0;
 
        // Initially 100 in binary
        // if n is 3 as
        // 1<<(3-1) = 100 in binary
        int num = 1 << (n - 1);
 
        // Iterate in the array
        // and assign signs to
        // the array elements
        for (int j = 0; j < n; j++)
        {
 
            // If the j-th bit
            // from left is set
            // take '+' sign
            if ((i & num) > 0)
                sum += a[j];
            else
                sum += (-1 * a[j]);
 
            // Right shift to check if
            // jth bit is set or not
            num = num >> 1;
        }
 
        if (sum % m == 0)
        {
 
            // re-initialize
            num = 1 << (n - 1);
 
            // Iterate in the
            // array elements
            for (int j = 0; j < n; j++)
            {
 
                // If the jth from
                // left is set
                if ((i & num) > 0)
                    System.out.print("+" +
                                     a[j] + " ");
                else
                    System.out.print("-" +
                                     a[j] + " ");
 
                // right shift
                num = num >> 1;
            }
             
        System.out.println();
        }
    }
}
 
// Driver code
public static void main(String args[])
{
    int a[] = { 3, 5, 6, 8 };
    int n = a.length;
    int m = 5;
 
    printCombinations(a, n, m);
}
}
 
// This code is contributed
// by inder_verma.


Python3
# Function to print
# all the combinations
def printCombinations(a, n, m):
 
    # Iterate for all
    # combinations
    for i in range(0, (1 << n)):
     
        sum = 0
 
        # Initially 100 in binary
        # if n is 3 as
        # 1<<(3-1) = 100 in binary
        num = 1 << (n - 1)
 
        # Iterate in the array
        # and assign signs to
        # the array elements
        for j in range(0, n):
         
            # If the j-th bit
            # from left is set
            # take '+' sign
            if ((i & num) > 0):
                sum += a[j]
            else:
                sum += (-1 * a[j])
 
            # Right shift to check if
            # jth bit is set or not
            num = num >> 1
 
        if (sum % m == 0):
         
            # re-initialize
            num = 1 << (n - 1)
 
            # Iterate in the
            # array elements
            for j in range(0, n):
 
                # If the jth from
                # left is set
                if ((i & num) > 0):
                    print("+", a[j], end = " ",
                                     sep = "")
                else:
                    print("-", a[j], end = " ",
                                     sep = "")
 
                # right shift
                num = num >> 1
            print("")
     
# Driver code
a = [ 3, 5, 6, 8 ]
n = len(a)
m = 5
printCombinations(a, n, m)
 
# This code is contributed
# by smita.


C#
// Print all the combinations
// of N elements by changing
// sign such that their sum
// is divisible by M
using System;
 
class GFG
{
     
// Function to print
// all the combinations
static void printCombinations(int []a,
                              int n, int m)
{
 
    // Iterate for all
    // combinations
    for (int i = 0;
             i < (1 << n); i++)
    {
        int sum = 0;
 
        // Initially 100 in binary
        // if n is 3 as
        // 1<<(3-1) = 100 in binary
        int num = 1 << (n - 1);
 
        // Iterate in the array
        // and assign signs to
        // the array elements
        for (int j = 0; j < n; j++)
        {
 
            // If the j-th bit
            // from left is set
            // take '+' sign
            if ((i & num) > 0)
                sum += a[j];
            else
                sum += (-1 * a[j]);
 
            // Right shift to check if
            // jth bit is set or not
            num = num >> 1;
        }
 
        if (sum % m == 0)
        {
 
            // re-initialize
            num = 1 << (n - 1);
 
            // Iterate in the
            // array elements
            for (int j = 0; j < n; j++)
            {
 
                // If the jth from
                // left is set
                if ((i & num) > 0)
                    Console.Write("+" +
                              a[j] + " ");
                else
                    Console.Write("-" +
                              a[j] + " ");
 
                // right shift
                num = num >> 1;
            }
             
        Console.Write("\n");
        }
    }
}
 
// Driver code
public static void Main()
{
    int []a = { 3, 5, 6, 8 };
    int n = a.Length;
    int m = 5;
 
    printCombinations(a, n, m);
}
}
 
// This code is contributed
// by Smitha.


PHP
> 1;
        }
 
        if ($sum % $m == 0)
        {
 
            // re-initialize
            $num = 1 << ($n - 1);
 
            // Iterate in the array elements
            for ($j = 0; $j < $n; $j++)
            {
 
                // If the jth from left is set
                if (($i & $num))
                    echo "+" , $a[$j] , " ";
                else
                    echo "-" , $a[$j] , " ";
 
                // right shift
                $num = $num >> 1;
            }
        echo "\n";
        }
    }
}
 
// Driver Code
$a = array( 3, 5, 6, 8 );
$n = sizeof($a);
$m = 5;
 
printCombinations($a, $n, $m);
 
// This code is contributed by ajit
?>


Javascript


输出:
-3 -5 +6 -8 
-3 +5 +6 -8 
+3 -5 -6 +8 
+3 +5 -6 +8

时间复杂度: O(2 N * N),其中N是元素数。