📌  相关文章
📜  从给定数组中计算总和为 K 的四元组

📅  最后修改于: 2021-10-27 08:14:48             🧑  作者: 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


Javascript


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


Javascript


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


Javascript


输出:

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

蟒蛇3

# 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

Javascript


输出:

3

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

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

  1. 初始化计数器计数以存储具有给定总和S的总四元组和一个映射以存储每个可能的四元组的前两个元素的所有可能的总和。
  2. 使用变量i[0, N – 1]范围内遍历给定数组其中arr[i]是固定的第三个元素。
  3. 然后对于上述步骤中的每个元素arr[i] ,使用变量 j 在范围[i + 1, N – 1] 上遍历给定数组,并通过map[arr[i] + arr[j]递增计数器计数]
  4. 从上述循环遍历后,对于每个元素arr[i] ,从j = 0 到 i – 1遍历数组arr[]并增加前两个元素的任何和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

蟒蛇3

# 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

Javascript


输出:

3

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程