The Wayback Machine - https://web.archive.org/web/20240926221559/https://www.geeksforgeeks.org/sum-subsets-dynamic-programming/
Open In App

Sum over Subsets | Dynamic Programming

Last Updated : 29 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Basic Dynamic Programming, Bitmasks 
Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. 
Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bitwise subset of mask x, if x&i==i.
Examples: 
 

Input: A[] = {7, 12, 14, 16} , n = 2 Output: 7, 19, 21, 49 Explanation: There will be 4 values of x: 0,1,2,3 So, we need to calculate F(0),F(1),F(2),F(3). Now, F(0) = A0 = 7 F(1) = A0 + A1 = 19 F(2) = A0 + A2 = 21 F(3) = A0 + A1 + A2 + A3 = 49 Input: A[] = {7, 11, 13, 16} , n = 2 Output: 7, 18, 20, 47 Explanation: There will be 4 values of x: 0,1,2,3 So, we need to calculate F(0),F(1),F(2),F(3). Now, F(0) = A0 = 7 F(1) = A0 + A1 = 18 F(2) = A0 + A2 = 20 F(3) = A0 + A1 + A2 + A3 = 47


 


Brute-Force Approach: 
Iterate for all the x from 0 to (2n-1) . Calculate the bitwise subsets of all the x and sum it up for every x.
Time-Complexity: O(4^n)
Below is the implementation of above idea:
 

C++

// CPP program for brute force
// approach of SumOverSubsets DP
#include <bits/stdc++.h>
using namespace std;
  
// function to print the sum over subsets value
void SumOverSubsets(int a[], int n) {
  
  // array to store the SumOverSubsets
  int sos[1 << n] = {0};
  
  // iterate for all possible x
  for (int x = 0; x < (1 << n); x++) {
  
    // iterate for all possible bitwise subsets
    for (int i = 0; i < (1 << n); i++) {
  
      // if i is a bitwise subset of x
      if ((x & i) == i)
        sos[x] += a[i];
    }
  }
  
  // printa all the subsets
  for (int i = 0; i < (1 << n); i++)
    cout << sos[i] << " ";
}
  
// Driver Code
int main() {
  int a[] = {7, 12, 14, 16};
  int n = 2;
  SumOverSubsets(a, n);
  return 0;
}

Java

// Java program for brute force
// approach of SumOverSubsets DP
  
class GFG{
  
// function to print the
// sum over subsets value
static void SumOverSubsets(int a[], int n) {
  
// array to store the SumOverSubsets
int sos[] = new int [1 << n];
  
  
// iterate for all possible x
for (int x = 0; x < (1 << n); x++) {
  
    // iterate for all possible
        // bitwise subsets
    for (int i = 0; i < (1 << n); i++) {
  
    // if i is a bitwise subset of x
    if ((x & i) == i)
        sos[x] += a[i];
    }
}
  
// printa all the subsets
for (int i = 0; i < (1 << n); i++)
    System.out.printf("%d ", sos[i]);
}
  
// Driver Code
public static void main(String[] args) {
int a[] = {7, 12, 14, 16};
int n = 2;
SumOverSubsets(a, n);
}
}
  
// This code is contributed by 
// Smitha Dinesh Semwal

Python3

# Python 3 program
# for brute force
# approach of SumOverSubsets DP
  
# function to print the
# sum over subsets value
def SumOverSubsets(a, n):
  
    # array to store
    # the SumOverSubsets
    sos = [0] * (1 << n)
      
    # iterate for all possible x
    for x in range(0,(1 << n)): 
      
        # iterate for all
        # possible bitwise subsets
        for i in range(0,(1 << n)):  
      
            # if i is a bitwise subset of x
            if ((x & i) == i):
                sos[x] += a[i]
              
      
      
    # printa all the subsets
    for i in range(0,(1 << n)): 
        print(sos[i],end = " ")
  
  
# Driver Code
a = [7, 12, 14, 16]
n = 2
SumOverSubsets(a, n)
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program for brute force
// approach of SumOverSubsets DP
using System;
  
class GFG {
      
    // function to print the
    // sum over subsets value
    static void SumOverSubsets(int []a, int n)
    {
      
        // array to store the SumOverSubsets
        int []sos = new int [1 << n];
          
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) 
        {
          
            // iterate for all possible
            // bitwise subsets
            for (int i = 0; i < (1 << n); i++) 
            {
          
                // if i is a bitwise subset of x
                if ((x & i) == i)
                    sos[x] += a[i];
            }
        }
          
        // printa all the subsets
        for (int i = 0; i < (1 << n); i++)
            Console.Write(sos[i] + " ");
    }
      
    // Driver function
    public static void Main()
    {
        int []a = {7, 12, 14, 16};
        int n = 2;
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007

PHP

<?php
// PHP program for brute force
// approach of SumOverSubsets DP
  
// function to print the sum 
// over subsets value
function SumOverSubsets($a, $n)
{
  
    // array to store the SumOverSubsets
    $sos = array(1 << $n);
      
    for($i = 0 ;$i < (1 << $n); $i++)
        $sos[$i] = 0; 
      
    // iterate for all possible x
    for ($x = 0; $x < (1 << $n); $x++)
    {
      
        // iterate for all possible 
        // bitwise subsets
        for($i = 0; $i < (1 << $n); $i++)
        {
      
            // if i is a bitwise
            // subset of x
            if (($x & $i) == $i)
                $sos[$x] += $a[$i];
        }
    }
      
    // printa all the subsets
    for ($i = 0; $i < (1 << $n); $i++)
        echo $sos[$i] . " ";
}
  
// Driver Code
$a = array(7, 12, 14, 16);
$n = 2;
SumOverSubsets($a, $n);
  
// This code is contributed by Sam007
?>

Javascript

<script>
    // Javascript program for brute force
    // approach of SumOverSubsets DP
      
    // function to print the
    // sum over subsets value
    function SumOverSubsets(a, n)
    {
       
        // array to store the SumOverSubsets
        let sos = new Array(1 << n);
        sos.fill(0);
           
           
        // iterate for all possible x
        for (let x = 0; x < (1 << n); x++)
        {
           
            // iterate for all possible
            // bitwise subsets
            for (let i = 0; i < (1 << n); i++)
            {
           
                // if i is a bitwise subset of x
                if ((x & i) == i)
                    sos[x] += a[i];
            }
        }
           
        // printa all the subsets
        for (let i = 0; i < (1 << n); i++)
            document.write(sos[i] + " ");
    }
      
    let a = [7, 12, 14, 16];
    let n = 2;
    SumOverSubsets(a, n);
          
</script>

Output: 
 

7 19 21 49

. 
Sub-Optimal Approach: 
The brute-force algorithm can be easily improved by just iterating over bitwise subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&x gives us every bitwise subset, where i starts from x and ends at 1. If the mask x has k set bits, we do 2k iterations. A number of k set bits will have 2k bitwise subsets. Therefore total number of mask x with k set bits is[Tex]{n \choose k}          [/Tex]. Therefore the total number of iterations is ?[Tex]{n \choose k}          [/Tex]2k = 3n 
Time Complexity: O(3n)
Below is the implementation of above idea: 
 

C++

// CPP program for sub-optimal
// approach of SumOverSubsets DP
#include <bits/stdc++.h>
using namespace std;
  
// function to print the sum over subsets value
void SumOverSubsets(int a[], int n) {
  
  // array to store the SumOverSubsets
  int sos[1 << n] = {0};
  
  // iterate for all possible x
  for (int x = 0; x < (1 << n); x++) {
    sos[x] = a[0];
  
    // iterate for the bitwise subsets only
    for (int i = x; i > 0; i = (i - 1) & x)
      sos[x] += a[i];
  }
  
  // print all the subsets
  for (int i = 0; i < (1 << n); i++)
    cout << sos[i] << " ";
}
  
// Driver Code
int main() {
  int a[] = {7, 12, 14, 16};
  int n = 2;
  SumOverSubsets(a, n);
  return 0;
}

Java

// java program for sub-optimal
// approach of SumOverSubsets DP
public class GFG {
      
    // function to print the sum over
    // subsets value
    static void SumOverSubsets(int a[], int n)
    {
      
        // array to store the SumOverSubsets
        int sos[] = new int[(1 << n)];
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
          
            // iterate for the bitwise subsets only
            for (int i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
          
        // print all the subsets
        for (int i = 0; i < (1 << n); i++)
            System.out.print(sos[i] + " ");
    }
      
    // Driver code
    public static void main(String args[])
    {
        int a[] = {7, 12, 14, 16};
        int n = 2;
          
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007

Python3

# Python program for sub-optimal
# approach of SumOverSubsets DP
  
# function to print sum over subsets value
def SumOverSubsets(a, n):
    sos = [0]*(1 << n)
  
    # iterate for all possible x
    for x in range((1 << n)):
        sos[x] = a[0]
          
        # iterate for the bitwise subsets only
        i = x
  
        while i > 0:
          sos[x] += a[i]
          i = ((i - 1) & x)
  
  # print all the subsets
    for i in range(1<<n):
        print(sos[i], end = " ")
  
# Driver Code
if __name__ == '__main__':
    a = [7, 12, 14, 16]
    n = 2
    SumOverSubsets(a, n)
  
# This code is contributed by mohit kumar 29.

C#

// C# program for sub-optimal
// approach of SumOverSubsets DP
using System;
  
class GFG {
      
    // function to print the sum over
    // subsets value
    static void SumOverSubsets(int []a, int n)
    {
      
        // array to store the SumOverSubsets
        int []sos = new int[(1 << n)];
          
        // iterate for all possible x
        for (int x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
          
            // iterate for the bitwise subsets only
            for (int i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
          
        // print all the subsets
        for (int i = 0; i < (1 << n); i++)
        Console.Write(sos[i] + " ");
    }
      
    // Driver code
    static void Main()
    {
        int []a = {7, 12, 14, 16};
        int n = 2;
          
        SumOverSubsets(a, n);
    }
}
  
// This code is contributed by Sam007.

PHP

<?php
// PHP program for sub-optimal
// approach of SumOverSubsets DP
  
// function to print the 
// sum over subsets value
function SumOverSubsets($a,$n) 
{
  
    // array to store the SumOverSubsets
    $sos=array(1 << $n);
      
    // iterate for all possible x
    for ($x = 0; $x < (1 << $n); $x++) 
    {
        $sos[$x] = $a[0];
      
        // iterate for the bitwise
        // subsets only
        for ($i = $x; $i > 0; $i = ($i - 1) & $x)
        $sos[$x] += $a[$i];
    }
      
    // print all the subsets
    for ($i = 0; $i < (1 << $n); $i++)
        echo $sos[$i] . " ";
}
  
// Driver Code
$a = array(7, 12, 14, 16);
$n = 2;
SumOverSubsets($a, $n);
  
// This code is contributed by Sam007.
?>

Javascript

<script>    
    // Javascript program for sub-optimal
    // approach of SumOverSubsets DP
      
    // function to print the sum over
    // subsets value
    function SumOverSubsets(a, n)
    {
       
        // array to store the SumOverSubsets
        let sos = new Array((1 << n));
        sos.fill(0);
           
        // iterate for all possible x
        for (let x = 0; x < (1 << n); x++) {
            sos[x] = a[0];
           
            // iterate for the bitwise subsets only
            for (let i = x; i > 0; i = (i - 1) & x)
                sos[x] += a[i];
        }
           
        // print all the subsets
        for (let i = 0; i < (1 << n); i++)
            document.write(sos[i] + " ");
    }
      
    let a = [7, 12, 14, 16];
    let n = 2;
  
    SumOverSubsets(a, n);
  
</script>


Output: 
 

7 19 21 49

Time Complexity: O(n*2n) 

Auxiliary Space: O(2n)

Reference: 



Previous Article
Next Article

Similar Reads

Count of index subsets such that maximum of values over these indices in A is at least total sum over B
Given two arrays A[] and B[] consisting of N positive integers, the task is to find the total number of subsets of indices such that the maximum value in the array A[] over all these indices is greater than or equal to the sum of all values over these indices in the array B[]. Examples: Input: A[] = {3, 1}, B[] = {1, 2}Output: 2Explanation:The tota
11 min read
Divide array in two Subsets such that sum of square of sum of both subsets is maximum
Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1
6 min read
Sum of subsets of all the subsets of an array | O(3^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(2^N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
6 min read
Sum of subsets of all the subsets of an array | O(N)
Given an array arr[] of length N, the task is to find the overall sum of subsets of all the subsets of the array.Examples: Input: arr[] = {1, 1} Output: 6 All possible subsets: a) {} : 0 All the possible subsets of this subset will be {}, Sum = 0 b) {1} : 1 All the possible subsets of this subset will be {} and {1}, Sum = 0 + 1 = 1 c) {1} : 1 All t
7 min read
Find sum of difference of maximum and minimum over all possible subsets of size K
Given an array arr[] of N integers and an integer K, the task is to find the sum of the difference between the maximum and minimum elements over all possible subsets of size K. Examples: Input: arr[] = {1, 1, 3, 4}, K = 2Output: 11Explanation:There are 6 subsets of the given array of size K(= 2). They are {1, 1}, {1, 3}, {1, 4}, {1, 3}, {1, 4} and
12 min read
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Maximum number of subsets an array can be split into such that product of their minimums with size of subsets is at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of disjoint subsets that the given array can be split into such that the product of the minimum element of each subset with the size of the subset is at least K. Examples: Input: arr[] = {7, 11, 2, 9, 5}, K = 10Output: 2Explanation:All such disjoi
8 min read
Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first subset is minimum. If there is still a tie then p
14 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.Examples:
9 min read
Count of numbers from range [L, R] whose sum of digits is Y using Dynamic Programming
Pre-requisites: Recursion, Dynamic Programming, Digit DP Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples: Input: L = 0, R = 11, Y = 2 Output: 2 2 -> 2 11 -> 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3 Constraints: 0 <= L <= R <=
10 min read
Sum of sum of all subsets of a set formed by first N natural numbers
Given N, and ff(N) = f(1) + f(2) + ...... + f(N), where f(k) is the sum of all subsets of a set formed by first k natural numbers. The task is to find ff(N) modulo 1000000007. Examples: Input: 2 Output: 7 f(1) + f(2) f(1) = 1 = 1 f(2) = 1 + 2 + {1 + 2} = 6 Input: 3 Output: 31 f(1) + f(2) + f(3) f(1) = 1 = 1 f(2) = 1 + 2 + {1 + 2} = 6 f(3) = 1 + 2 +
11 min read
Rearrange an Array such that Sum of same-indexed subsets differ from their Sum in the original Array
Given an array A[] consisting of N distinct integers, the task is to rearrange the given array such that the sum of every same-indexed non-empty subsets of size less than N, is not equal to their sum in the original array.Examples: Input: A[] = {1000, 100, 10, 1} Output: 100 10 1 1000 Explanation: Original Array A[] = {1000, 100, 10, 1} Final Array
6 min read
Sum of all subsets whose sum is a Perfect Number from a given array
Given an array arr[] consisting of N integers, the task is to find the sum of all subsets from an array, whose sum is a Perfect Number. Examples: Input: arr[] = {5, 4, 6}Output: 6Explanation:All possible subsets from the array arr[] are:{5} ? Sum = 5{4} ? Sum = 4.{6} ? Sum = 6.{5, 4} ? Sum = 9.{5, 6} ? Sum = 11.{4, 6} ? Sum = 10.{5, 4, 6} ? Sum = 1
14 min read
Sum of length of two smallest subsets possible from a given array with sum at least K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the length of the two smallest unique subsets having sum of its elements at least K. Examples: Input: arr[] = {2, 4, 5, 6, 7, 8}, K = 16Output: 6Explanation:The subsets {2, 6, 8} and {4, 5, 7} are the two smallest subsets with sum K(= 16).Therefore, the s
15+ min read
Count of subsets with sum one less than the sum of Array
Given an array arr[ ] of size N. The task is to find the no of subsets with sum as (sum of the array - 1) when 0 occurs in an array or return -1 if there is no subset possible. Examples: Input: arr[ ] : {3, 0, 5, 2, 4} Output: -1Explanation: sum of array arr[ ] is 14 and there is not any subset with sum 13.Input: arr[ ] : {0, 0, 2, 1} Output: 4Expl
12 min read
Perfect Sum Problem (Print all subsets with given sum)
Given an array of integers and a sum, the task is to print all subsets of the given array with a sum equal to a given sum. Examples: Input : arr[] = {2, 3, 5, 6, 8, 10} sum = 10 Output : 5 2 3 2 8 10 Input : arr[] = {1, 2, 3, 4, 5} sum = 10 Output : 4 3 2 1 5 3 2 5 4 1 Asked in Tesco Recommended PracticePerfect Sum ProblemTry It! This problem is ma
15 min read
Introduction to Dynamic Programming on Trees
Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied on trees to solve some specific problems.Pre-requisite: DFSGiven a tree with N nodes and N-1 edges
10 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1->3->2->4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read
Minimum time required to rot all oranges | Dynamic Programming
Given a matrix of dimension m * n where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: 0: Empty cell 1: Cells have fresh oranges 2: Cells have rotten oranges So the task is to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh or
15 min read
Reliability Design Problem in Dynamic Programming
The reliability design problem is the designing of a system composed of several devices connected in series or parallel. Reliability means the probability to get the success of the device. Let's say, we have to set up a system consisting of D1, D2, D3, ............, and Dn devices, each device has some costs C1, C2, C3, ........, Cn. Each device ha
6 min read
Convert N to M with given operations using dynamic programming
Given two integers N and M and the task is to convert N to M with the following operations: Multiply N by 2 i.e. N = N * 2.Subtract 1 from N i.e. N = N - 1. Examples: Input: N = 4, M = 6 Output: 2 Perform operation 2: N = N - 1 = 4 - 1 = 3 Perform operation 1: N = N * 2 = 3 * 2 = 6 Input: N = 10, M = 1 Output: 9 Approach: Create an array dp[] of si
7 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Ackermann's function using Dynamic programming
Given two non-zero integers M and N, the problem is to compute the result of the Ackermann function based on some particular equations. Ackermann function is defined as: Examples: Input: M = 2, N = 2Output: 7 Input: M = 2, N = 7Output: 6141004759 The approach for Ackermann function described in this article, takes a very huge amount of time to comp
13 min read
Count ways to select N pairs of candies of distinct colors (Dynamic Programming + Bitmasking)
Given an integer N representing the number of red and blue candies and a matrix mat[][] of size N * N, where mat[i][j] = 1 represents the existence of a pair between ith red candy and jth blue candy, the task is to find the count of ways to select N pairs of candies such that each pair contains distinct candies of different colors. Examples: Input:
13 min read