📜  使用递归计算总和等于 X 的子集数

📅  最后修改于: 2021-09-03 14:57:32             🧑  作者: Mango

给定一个长度为N的数组arr[]和一个整数X ,任务是使用递归找到总和等于X的子集的数量。
例子:

方法:想法是递归检查所有子集。如果任何子集的总和等于 N,则将计数增加 1。否则,继续。
为了形成子集,每个元素有两种情况:

  • 将元素包含在集合中。
  • 排除集合中的元素。

因此,可以按照以下步骤来计算答案:

  1. 获取要找到总和等于 K 的子集的数组。
  2. 按以下方式递归计算总和等于 K 的子集:
    • 基本情况:基本情况将是到达数组末尾时。如果在这里找到的总和为 X,则将子集的计数增加 1。返回在基本条件中计算的计数。
      if (i == n) {
          if (sum == 0)
              count++;
          return count;
      }
  • 递归调用:如果不满足基本情况,则调用该函数两次。一次包含索引 ‘i’ 处的元素,一次不包含该元素。找到这两种情况的计数,然后返回最终计数。
    count = subsetSum(arr, n, i + 1, sum - arr[i], count);
    count = subsetSum(arr, n, i + 1, sum, count);
  • 返回语句:在每一步,通过包含特定元素或不包含特定元素返回子集的计数。最后,当整个递归堆栈被执行时,返回总计数。

从上面的做法可以清楚的分析出,如果数组中有N个元素,那么一共出现2N种情况。使用递归检查上述情况的每个元素。
下面是上述方法的实现:

C++
// C++ program to print the count of
// subsets with sum equal to the given value X
  
#include 
using namespace std;
  
// Recursive function to return the count
// of subsets with sum equal to the given value
int subsetSum(int arr[], int n, int i,
              int sum, int count)
{
    // The recursion is stopped at N-th level
    // where all the subsets of the given array
    // have been checked
    if (i == n) {
  
        // Incrementing the count if sum is
        // equal to 0 and returning the count
        if (sum == 0) {
            count++;
        }
        return count;
    }
  
    // Recursively calling the function for two cases
    // Either the element can be counted in the subset
    // If the element is counted, then the remaining sum
    // to be checked is sum - the selected element
    // If the element is not included, then the remaining sum
    // to be checked is the total sum
    count = subsetSum(arr, n, i + 1, sum - arr[i], count);
    count = subsetSum(arr, n, i + 1, sum, count);
    return count;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int sum = 10;
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << subsetSum(arr, n, 0, sum, 0);
}


Java
// Java program to print the count of
// subsets with sum equal to the given value X
import java.util.*;
  
class GFG
{
  
// Recursive function to return the count
// of subsets with sum equal to the given value
static int subsetSum(int arr[], int n, int i,
                    int sum, int count)
{
    // The recursion is stopped at N-th level
    // where all the subsets of the given array
    // have been checked
    if (i == n) 
    {
  
        // Incrementing the count if sum is
        // equal to 0 and returning the count
        if (sum == 0) 
        {
            count++;
        }
        return count;
    }
  
    // Recursively calling the function for two cases
    // Either the element can be counted in the subset
    // If the element is counted, then the remaining sum
    // to be checked is sum - the selected element
    // If the element is not included, then the remaining sum
    // to be checked is the total sum
    count = subsetSum(arr, n, i + 1, sum - arr[i], count);
    count = subsetSum(arr, n, i + 1, sum, count);
    return count;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int sum = 10;
    int n = arr.length;
  
    System.out.print(subsetSum(arr, n, 0, sum, 0));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to print the count of
# subsets with sum equal to the given value X
  
# Recursive function to return the count
# of subsets with sum equal to the given value
def subsetSum(arr, n, i,sum, count):
      
    # The recursion is stopped at N-th level
    # where all the subsets of the given array
    # have been checked
    if (i == n):
  
        # Incrementing the count if sum is
        # equal to 0 and returning the count
        if (sum == 0):
            count += 1
        return count
  
    # Recursively calling the function for two cases
    # Either the element can be counted in the subset
    # If the element is counted, then the remaining sum
    # to be checked is sum - the selected element
    # If the element is not included, then the remaining sum
    # to be checked is the total sum
    count = subsetSum(arr, n, i + 1, sum - arr[i], count)
    count = subsetSum(arr, n, i + 1, sum, count)
    return count
  
# Driver code
arr = [1, 2, 3, 4, 5]
sum = 10
n = len(arr)
  
print(subsetSum(arr, n, 0, sum, 0))
  
# This code is contributed by mohit kumar 29


C#
// C# program to print the count of
// subsets with sum equal to the given value X
using System;
  
class GFG
{
  
// Recursive function to return the count
// of subsets with sum equal to the given value
static int subsetSum(int []arr, int n, int i,
                    int sum, int count)
{
    // The recursion is stopped at N-th level
    // where all the subsets of the given array
    // have been checked
    if (i == n) 
    {
  
        // Incrementing the count if sum is
        // equal to 0 and returning the count
        if (sum == 0) 
        {
            count++;
        }
        return count;
    }
  
    // Recursively calling the function for two cases
    // Either the element can be counted in the subset
    // If the element is counted, then the remaining sum
    // to be checked is sum - the selected element
    // If the element is not included, then the remaining sum
    // to be checked is the total sum
    count = subsetSum(arr, n, i + 1, sum - arr[i], count);
    count = subsetSum(arr, n, i + 1, sum, count);
    return count;
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4, 5 };
    int sum = 10;
    int n = arr.Length;
  
    Console.Write(subsetSum(arr, n, 0, sum, 0));
}
}
  
// This code is contributed by PrinciRaj1992


Javascript


输出:
3

有效的方法:
本文讨论了使用动态规划解决问题的有效方法。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live