📜  用给定数组的总和K计算四倍体

📅  最后修改于: 2021-05-17 17:53:18             🧑  作者: Mango

给定大小为N的数组arr []和整数S ,任务是查找给定数组中总和为S的四元组的计数。

例子:

天真的方法:这个想法是从给定的数组中生成长度为4的所有可能组合。对于每个四元组,如果总和等于S ,则将计数器增加1 。在检查完所有四元组之后,将计数器打印为总和为S的四元组的总数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to return the number of
// quadruplets with the given sum
int countSum(int a[], int n, int sum)
{
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for (i = 0; i < n - 3; i++) {
 
        // All possible second elements
        for (j = i + 1; j < n - 2; j++) {
 
            // All possible third elements
            for (k = j + 1; k < n - 1; k++) {
 
                // All possible fourth elements
                for (l = k + 1; l < n; l++) {
 
                    // Increment counter by 1
                    // if quadruplet sum is S
                    if (a[i] + a[j]
                            + a[k] + a[l]
                        == sum)
                        count++;
                }
            }
        }
    }
 
    // Return the final count
    return count;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSum(arr, N, S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
   
// Function to return the number of
// quadruplets with the given sum
static int countSum(int a[], int n, int sum)
{
     
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second elements
        for(j = i + 1; j < n - 2; j++)
        {
             
            // All possible third elements
            for(k = j + 1; k < n - 1; k++)
            {
                 
                // All possible fourth elements
                for(l = k + 1; l < n; l++)
                {
                     
                    // Increment counter by 1
                    // if quadruplet sum is S
                    if (a[i] + a[j] +
                        a[k] + a[l] == sum)
                        count++;
                }
            }
        }
    }
 
    // Return the final count
    return count;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.length;
 
    // Function Call
    System.out.print(countSum(arr, N, S));
}
}
 
// This code is contributed by bgangwar59


Python3
# Python3 program for the above approach
 
# Function to return the number of
# quadruplets with the given sum
def countSum(a, n, sum):
     
    # Initialize variables
    # i, j, k, l
 
    # Initialize answer
    count = 0
 
    # All possible first elements
    for i in range(n - 3):
         
        # All possible second elements
        for j in range(i + 1, n - 2):
             
            # All possible third elements
            for k in range(j + 1, n - 1):
                 
                # All possible fourth elements
                for l in range(k + 1, n):
                     
                    # Increment counter by 1
                    # if quadruplet sum is S
                    if (a[i] + a[j] + a[k] + a[l]== sum):
                        count += 1
                         
    # Return the final count
    return count
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr = [ 4, 5, 3, 1, 2, 4 ]
 
    # Given sum S
    S = 13
 
    N = len(arr)
     
    # Function Call
    print(countSum(arr, N, S))
     
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
class GFG{
   
// Function to return the number of
// quadruplets with the given sum
static int countSum(int []a, int n, int sum)
{
     
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second elements
        for(j = i + 1; j < n - 2; j++)
        {
             
            // All possible third elements
            for(k = j + 1; k < n - 1; k++)
            {
                 
                // All possible fourth elements
                for(l = k + 1; l < n; l++)
                {
                     
                    // Increment counter by 1
                    // if quadruplet sum is S
                    if (a[i] + a[j] +
                        a[k] + a[l] == sum)
                        count++;
                }
            }
        }
    }
 
    // Return the final count
    return count;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int []arr = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.Length;
 
    // Function Call
    System.Console.Write(countSum(arr, N, S));
}
}
 
// This code is contributed by SURENDRA_GANGWAR


C++
// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to return the number of
// quadruplets having given sum
int countSum(int a[], int n, int sum)
{
 
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for (i = 0; i < n - 3; i++) {
 
        // All possible second element
        for (j = i + 1; j < n - 2; j++) {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            unordered_map m;
 
            // All possible third elements
            for (k = j + 1; k < n; k++)
                m[a[k]]++;
 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for (k = j + 1; k < n; k++) {
 
                // Update the twice_count
                twice_count += m[req - a[k]];
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSum(arr, N, S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to return the number of
// quadruplets having given sum
static int countSum(int a[], int n, int sum)
{
     
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second element
        for(j = i + 1; j < n - 2; j++)
        {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            HashMap m = new HashMap<>();
 
            // All possible third elements
            for(k = j + 1; k < n; k++)
                if (m.containsKey(a[k]))
                {
                    m.put(a[k], m.get(a[k]) + 1);
                }
                else
                {
                    m.put(a[k], 1);
                }
                 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for(k = j + 1; k < n; k++)
            {
                 
                // Update the twice_count
                if (m.containsKey(req - a[k]))
                    twice_count += m.get(req - a[k]);
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.length;
 
    // Function Call
    System.out.print(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above approach
 
# Function to return the number of
# quadruplets having given sum
def countSum(a, n, sum):
     
    # Initialize variables
    # Initialize answer
    count = 0
 
    # All possible first elements
    for i in range(n - 3):
         
        # All possible second element
        for j in range(i + 1, n - 2, 1):
            req = sum - a[i] - a[j]
 
            # Use map to find the
            # fourth element
            m = {}
 
            # All possible third elements
            for k in range(j + 1, n, 1):
                m[a[k]] = m.get(a[k], 0) + 1
 
            twice_count = 0
 
            # Calculate number of valid
            # 4th elements
            for k in range(j + 1, n, 1):
                 
                # Update the twice_count
                twice_count += m.get(req - a[k], 0)
 
                if (req - a[k] == a[k]):
                    twice_count -= 1
 
            # Unordered pairs
            count += twice_count // 2
 
    # Return answer
    return count
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr =  [ 4, 5, 3, 1, 2, 4 ]
 
    # Given sum S
    S = 13
 
    N =  len(arr)
 
    # Function Call
    print(countSum(arr, N, S))
 
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the number of
// quadruplets having given sum
static int countSum(int []a, int n,
                    int sum)
{
     
    // Initialize variables
    int i, j, k;
    //int l;
     
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second element
        for(j = i + 1; j < n - 2; j++)
        {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            Dictionary m = new Dictionary();
 
            // All possible third elements
            for(k = j + 1; k < n; k++)
                if (m.ContainsKey(a[k]))
                {
                    m[a[k]]++;
                }
                else
                {
                    m.Add(a[k], 1);
                }
                 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for(k = j + 1; k < n; k++)
            {
                 
                // Update the twice_count
                if (m.ContainsKey(req - a[k]))
                    twice_count += m[req - a[k]];
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.Length;
 
    // Function Call
    Console.Write(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh


C++
// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to return the number of
// quadruplets having the given sum
int countSum(int a[], int n, int sum)
{
 
    // Initialize variables
    int i, j, k;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    unordered_map m;
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for (i = 0; i < n - 1; i++) {
 
        // All possible 4th elements
        for (j = i + 1; j < n; j++) {
 
            // Sum of last two element
            int temp = a[i] + a[j];
 
            // Frequency of sum of first
            // two elements
            if (temp < sum)
                count += m[sum - temp];
        }
        for (j = 0; j < i; j++) {
 
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                m[temp]++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSum(arr, N, S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to return the number of
// quadruplets having the given sum
static int countSum(int a[], int n, int sum)
{
     
    // Initialize variables
    int i, j, k;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    HashMap m = new HashMap<>();
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for(i = 0; i < n - 1; i++)
    {
         
        // All possible 4th elements
        for(j = i + 1; j < n; j++)
        {
             
            // Sum of last two element
            int temp = a[i] + a[j];
 
            // Frequency of sum of first
            // two elements
            if (temp < sum && m.containsKey(sum - temp))
                count += m.get(sum - temp);
        }
        for(j = 0; j < i; j++)
        {
             
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                if (m.containsKey(temp))
                    m.put(temp, m.get(temp) + 1);
                else
                    m.put(temp, 1);
        }
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.length;
 
    // Function Call
    System.out.print(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above approach
from collections import defaultdict
 
# Function to return the number of
# quadruplets having the given sum
def countSum(a, n, sum):
     
    # Initialize answer
    count = 0
 
    # Store the frequency of sum
    # of first two elements
    m = defaultdict(int)
 
    # Traverse from 0 to N-1, where
    # arr[i] is the 3rd element
    for i in range(n - 1):
 
        # All possible 4th elements
        for j in range(i + 1, n):
 
            # Sum of last two element
            temp = a[i] + a[j]
 
            # Frequency of sum of first
            # two elements
            if (temp < sum):
                count += m[sum - temp]
 
        for j in range(i):
 
            # Store frequency of all possible
            # sums of first two elements
            temp = a[i] + a[j]
 
            if (temp < sum):
                m[temp] += 1
 
    # Return the answer
    return count
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [ 4, 5, 3, 1, 2, 4 ]
 
    # Given sum S
    S = 13
 
    N = len(arr)
 
    # Function Call
    print(countSum(arr, N, S))
 
# This code is contributed by chitranayal


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the number of
// quadruplets having the given sum
static int countSum(int []a, int n, int sum)
{
     
    // Initialize variables
    int i, j;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    Dictionary m = new Dictionary();
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for(i = 0; i < n - 1; i++)
    {
         
        // All possible 4th elements
        for(j = i + 1; j < n; j++)
        {
             
            // Sum of last two element
            int temp = a[i] + a[j];
             
            // Frequency of sum of first
            // two elements
            if (temp < sum && m.ContainsKey(sum - temp))
                count += m[sum - temp];
        }
         
        for(j = 0; j < i; j++)
        {
             
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                if (m.ContainsKey(temp))
                    m[temp]++;
                else
                    m.Add(temp, 1);
        }
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.Length;
     
    // Function Call
    Console.Write(countSum(arr, N, S));
}
}
 
// This code is contributed by shikhasingrajput


输出:

3

时间复杂度: O(N 4 )
辅助空间: O(N)

更好的方法:为了优化上述方法,我们的想法是使用Map数据结构。请按照以下步骤解决问题:

  • 0初始化计数器计数以存储四元组的数量。
  • 使用变量i遍历[0,N – 3)范围内的给定数组。对于每个元素arr [i] ,使用变量j[i + 1,N – 2)范围内再次遍历数组然后执行以下操作:
    • 找到所需总和的值(例如req )为(S – arr [i]-arr [j])
    • 0初始化count_twice ,它将以sum (S – arr [i]-arr [j])存储上述子数组中有序对的计数。
    • 找到count_twice之后,以count_twice / 2更新计数。
  • 完成上述步骤后,将count的值打印为结果。

下面是上述想法的实现:

C++

// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to return the number of
// quadruplets having given sum
int countSum(int a[], int n, int sum)
{
 
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for (i = 0; i < n - 3; i++) {
 
        // All possible second element
        for (j = i + 1; j < n - 2; j++) {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            unordered_map m;
 
            // All possible third elements
            for (k = j + 1; k < n; k++)
                m[a[k]]++;
 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for (k = j + 1; k < n; k++) {
 
                // Update the twice_count
                twice_count += m[req - a[k]];
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSum(arr, N, S);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to return the number of
// quadruplets having given sum
static int countSum(int a[], int n, int sum)
{
     
    // Initialize variables
    int i, j, k, l;
 
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second element
        for(j = i + 1; j < n - 2; j++)
        {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            HashMap m = new HashMap<>();
 
            // All possible third elements
            for(k = j + 1; k < n; k++)
                if (m.containsKey(a[k]))
                {
                    m.put(a[k], m.get(a[k]) + 1);
                }
                else
                {
                    m.put(a[k], 1);
                }
                 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for(k = j + 1; k < n; k++)
            {
                 
                // Update the twice_count
                if (m.containsKey(req - a[k]))
                    twice_count += m.get(req - a[k]);
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.length;
 
    // Function Call
    System.out.print(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh

Python3

# Python3 program for the above approach
 
# Function to return the number of
# quadruplets having given sum
def countSum(a, n, sum):
     
    # Initialize variables
    # Initialize answer
    count = 0
 
    # All possible first elements
    for i in range(n - 3):
         
        # All possible second element
        for j in range(i + 1, n - 2, 1):
            req = sum - a[i] - a[j]
 
            # Use map to find the
            # fourth element
            m = {}
 
            # All possible third elements
            for k in range(j + 1, n, 1):
                m[a[k]] = m.get(a[k], 0) + 1
 
            twice_count = 0
 
            # Calculate number of valid
            # 4th elements
            for k in range(j + 1, n, 1):
                 
                # Update the twice_count
                twice_count += m.get(req - a[k], 0)
 
                if (req - a[k] == a[k]):
                    twice_count -= 1
 
            # Unordered pairs
            count += twice_count // 2
 
    # Return answer
    return count
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr[]
    arr =  [ 4, 5, 3, 1, 2, 4 ]
 
    # Given sum S
    S = 13
 
    N =  len(arr)
 
    # Function Call
    print(countSum(arr, N, S))
 
# This code is contributed by ipg2016107

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the number of
// quadruplets having given sum
static int countSum(int []a, int n,
                    int sum)
{
     
    // Initialize variables
    int i, j, k;
    //int l;
     
    // Initialize answer
    int count = 0;
 
    // All possible first elements
    for(i = 0; i < n - 3; i++)
    {
         
        // All possible second element
        for(j = i + 1; j < n - 2; j++)
        {
            int req = sum - a[i] - a[j];
 
            // Use map to find the
            // fourth element
            Dictionary m = new Dictionary();
 
            // All possible third elements
            for(k = j + 1; k < n; k++)
                if (m.ContainsKey(a[k]))
                {
                    m[a[k]]++;
                }
                else
                {
                    m.Add(a[k], 1);
                }
                 
            int twice_count = 0;
 
            // Calculate number of valid
            // 4th elements
            for(k = j + 1; k < n; k++)
            {
                 
                // Update the twice_count
                if (m.ContainsKey(req - a[k]))
                    twice_count += m[req - a[k]];
 
                if (req - a[k] == a[k])
                    twice_count--;
            }
 
            // Unordered pairs
            count += twice_count / 2;
        }
    }
 
    // Return answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.Length;
 
    // Function Call
    Console.Write(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh

输出:

3

时间复杂度: O(N 3 ),其中N是给定数组的大小,
辅助空间: O(N)

高效方法:这个想法类似于上面使用地图的方法。用这种方法,固定第三个元素,然后找到并存储给定数组的任何四倍体的所有可能的前两个元素之和的频率。请按照以下步骤解决问题:

  1. 初始化计数器计数以存储具有给定总和S的总四元组,并存储一个映射以存储每个可能的四元组的前两个元素的所有可能的总和。
  2. 遍历过的范围中的给定阵列[0,N – 1]使用变量i其中ARR [i]是固定的第三元件。
  3. 然后,在上述步骤中,对于每个元素arr [i] ,使用变量j遍历[i + 1,N – 1]范围内的给定数组,并将计数器计数增加map [arr [i] + arr [j] ]
  4. 从上述循环遍历后,对于每个元素arr [i] ,将数组arr []j = 0遍历到i – 1,并递增前两个元素的任意和arr [i] + arr [j]的频率将任何可能的四元组乘以1,即,将map [arr [i] + arr [j]]乘以1
  5. 对每个元素arr [i]重复上述步骤,然后将计数器计数打印为具有给定总和S的四元组总数。

下面是上述想法的实现:

C++

// C++ program for the above approach
 
#include 
#include 
using namespace std;
 
// Function to return the number of
// quadruplets having the given sum
int countSum(int a[], int n, int sum)
{
 
    // Initialize variables
    int i, j, k;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    unordered_map m;
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for (i = 0; i < n - 1; i++) {
 
        // All possible 4th elements
        for (j = i + 1; j < n; j++) {
 
            // Sum of last two element
            int temp = a[i] + a[j];
 
            // Frequency of sum of first
            // two elements
            if (temp < sum)
                count += m[sum - temp];
        }
        for (j = 0; j < i; j++) {
 
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                m[temp]++;
        }
    }
 
    // Return the answer
    return count;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countSum(arr, N, S);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to return the number of
// quadruplets having the given sum
static int countSum(int a[], int n, int sum)
{
     
    // Initialize variables
    int i, j, k;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    HashMap m = new HashMap<>();
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for(i = 0; i < n - 1; i++)
    {
         
        // All possible 4th elements
        for(j = i + 1; j < n; j++)
        {
             
            // Sum of last two element
            int temp = a[i] + a[j];
 
            // Frequency of sum of first
            // two elements
            if (temp < sum && m.containsKey(sum - temp))
                count += m.get(sum - temp);
        }
        for(j = 0; j < i; j++)
        {
             
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                if (m.containsKey(temp))
                    m.put(temp, m.get(temp) + 1);
                else
                    m.put(temp, 1);
        }
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.length;
 
    // Function Call
    System.out.print(countSum(arr, N, S));
}
}
 
// This code is contributed by Princi Singh

Python3

# Python3 program for the above approach
from collections import defaultdict
 
# Function to return the number of
# quadruplets having the given sum
def countSum(a, n, sum):
     
    # Initialize answer
    count = 0
 
    # Store the frequency of sum
    # of first two elements
    m = defaultdict(int)
 
    # Traverse from 0 to N-1, where
    # arr[i] is the 3rd element
    for i in range(n - 1):
 
        # All possible 4th elements
        for j in range(i + 1, n):
 
            # Sum of last two element
            temp = a[i] + a[j]
 
            # Frequency of sum of first
            # two elements
            if (temp < sum):
                count += m[sum - temp]
 
        for j in range(i):
 
            # Store frequency of all possible
            # sums of first two elements
            temp = a[i] + a[j]
 
            if (temp < sum):
                m[temp] += 1
 
    # Return the answer
    return count
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [ 4, 5, 3, 1, 2, 4 ]
 
    # Given sum S
    S = 13
 
    N = len(arr)
 
    # Function Call
    print(countSum(arr, N, S))
 
# This code is contributed by chitranayal

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the number of
// quadruplets having the given sum
static int countSum(int []a, int n, int sum)
{
     
    // Initialize variables
    int i, j;
 
    // Initialize answer
    int count = 0;
 
    // Store the frequency of sum
    // of first two elements
    Dictionary m = new Dictionary();
 
    // Traverse from 0 to N-1, where
    // arr[i] is the 3rd element
    for(i = 0; i < n - 1; i++)
    {
         
        // All possible 4th elements
        for(j = i + 1; j < n; j++)
        {
             
            // Sum of last two element
            int temp = a[i] + a[j];
             
            // Frequency of sum of first
            // two elements
            if (temp < sum && m.ContainsKey(sum - temp))
                count += m[sum - temp];
        }
         
        for(j = 0; j < i; j++)
        {
             
            // Store frequency of all possible
            // sums of first two elements
            int temp = a[i] + a[j];
 
            if (temp < sum)
                if (m.ContainsKey(temp))
                    m[temp]++;
                else
                    m.Add(temp, 1);
        }
    }
     
    // Return the answer
    return count;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 4, 5, 3, 1, 2, 4 };
 
    // Given sum S
    int S = 13;
 
    int N = arr.Length;
     
    // Function Call
    Console.Write(countSum(arr, N, S));
}
}
 
// This code is contributed by shikhasingrajput

输出:

3

时间复杂度: O(N 2 )
辅助空间: O(N)