📌  相关文章
📜  总和小于数组总和的子序列计数

📅  最后修改于: 2022-05-13 01:56:10.073000             🧑  作者: Mango

总和小于数组总和的子序列计数

给定一个大小为N的非负整数数组vec[] 。任务是计算总和等于S – 2的子序列的数量,其中S是数组中所有元素的总和。

例子:

朴素方法:这个想法是生成所有子序列并检查每个子序列的总和是否等于S-2

下面是上述方法的实现。

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the total number
// of subsequences with sum S-2
void countTotal(vector& vec)
{
 
    // Calculating vector sum using
    // accumulate function
    int sum = accumulate(vec.begin(),
                         vec.end(), 0LL);
 
    int N = (int)vec.size();
 
    // Answer variable stores count
    // of subsequences with desired sum
    int answer = 0;
 
    // Bitmasking technique to generate
    // all possible subsequences
    for (int mask = 0; mask < (1 << N); mask++) {
 
        // Variable curr counts the
        // sum of the current subsequence
        int curr = 0;
        for (int i = 0; i < N; i++) {
 
            if ((mask & (1 << i)) != 0) {
 
                // Include ith element
                // of the vector
                curr += vec[i];
            }
        }
 
        if (curr == sum - 2)
            answer++;
    }
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
 
    // Initializing a vector
    vector vec = { 2, 0, 1, 2, 1 };
 
    countTotal(vec);
 
    return 0;
}


Java
// Java program for the above approach
public class GFG {
     
    static int accumulate(int [] vec){
        int sum1 = 0;
         
        for (int i = 0; i < vec.length; i++)
            sum1 += vec[i];
    return sum1;
    }
     
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int []vec)
    {
     
        // Calculating vector sum using
        // accumulate function
        int sum = accumulate(vec);
     
        int N = vec.length;
     
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
     
        // Bitmasking technique to generate
        // all possible subsequences
        for (int mask = 0; mask < (1 << N); mask++) {
     
            // Variable curr counts the
            // sum of the current subsequence
            int curr = 0;
            for (int i = 0; i < N; i++) {
     
                if ((mask & (1 << i)) != 0) {
     
                    // Include ith element
                    // of the vector
                    curr += vec[i];
                }
            }
     
            if (curr == sum - 2)
                answer++;
        }
     
        // Print the answer
        System.out.print(answer);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
     
        // Initializing a vector
        int []vec = { 2, 0, 1, 2, 1 };
     
        countTotal(vec);
    }
 
}
 
// This code is contributed by AnkThon


Python3
# python3 program for the above approach
 
# Function to count the total number
# of subsequences with sum S-2
def countTotal(vec) :
 
    # Calculating vector sum using
    # accumulate function
    Sum = sum(vec)
 
    N = len(vec);
 
    # Answer variable stores count
    # of subsequences with desired sum
    answer = 0;
 
    # Bitmasking technique to generate
    # all possible subsequences
    for mask in range((1 << N)) :
         
        # Variable curr counts the
        # sum of the current subsequence
        curr = 0;
        for i in range(N) :
 
            if ((mask & (1 << i)) != 0) :
 
                # Include ith element
                # of the vector
                curr += vec[i];
                 
        if (curr == Sum - 2) :
            answer += 1;
 
    # Print the answer
    print(answer);
 
# Driver Code
if __name__ == "__main__" :
 
 
    # Initializing a vector
    vec = [ 2, 0, 1, 2, 1 ];
 
    countTotal(vec);
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
 
public class GFG {
 
    static int accumulate(int[] vec)
    {
        int sum1 = 0;
 
        for (int i = 0; i < vec.Length; i++)
            sum1 += vec[i];
        return sum1;
    }
 
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int[] vec)
    {
 
        // Calculating vector sum using
        // accumulate function
        int sum = accumulate(vec);
 
        int N = vec.Length;
 
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
 
        // Bitmasking technique to generate
        // all possible subsequences
        for (int mask = 0; mask < (1 << N); mask++) {
 
            // Variable curr counts the
            // sum of the current subsequence
            int curr = 0;
            for (int i = 0; i < N; i++) {
 
                if ((mask & (1 << i)) != 0) {
 
                    // Include ith element
                    // of the vector
                    curr += vec[i];
                }
            }
 
            if (curr == sum - 2)
                answer++;
        }
 
        // Print the answer
        Console.WriteLine(answer);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        // Initializing a vector
        int[] vec = { 2, 0, 1, 2, 1 };
 
        countTotal(vec);
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the total number
// of subsequences with sum S-2
void countTotal(vector& vec)
{
 
    // Calculating vector sum using
    // accumulate function
    int sum = accumulate(vec.begin(),
                         vec.end(), 0LL);
 
    int N = (int)vec.size();
 
    // Answer variable stores count
    // of subsequences with desired sum
    int answer = 0;
 
    int countOfZero = 0,
        countOfOne = 0,
        countOfTwo = 0;
    for (auto x : vec) {
        if (x == 0)
            countOfZero++;
        else if (x == 1)
            countOfOne++;
        else if (x == 2)
            countOfTwo++;
    }
 
    // Select any number of
    // zeroes from 0 to count[0]
    // which is equivalent
    // to 2 ^ countOfZero
    int value1 = pow(2, countOfZero);
 
    // Considering all 2's
    // and extra elements
    int value2
        = (countOfOne
           * (countOfOne - 1))
          / 2;
 
    // Considering all 1's
    // and extra elements
    int value3 = countOfTwo;
 
    // Calculating final answer
    answer = value1 * (value2 + value3);
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
 
    // Initializing a vector
    vector vec = { 2, 0, 1, 2, 1 };
 
    countTotal(vec);
 
    return 0;
}


Java
/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int[] arr)
    {
 
        int N = arr.length;
 
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
 
        int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
        for (int i = 0; i < N; i++) {
 
            if (arr[i] == 0)
                countOfZero++;
            else if (arr[i] == 1)
                countOfOne++;
            else if (arr[i] == 2)
                countOfTwo++;
        }
 
        // Select any number of
        // zeroes from 0 to count[0]
        // which is equivalent
        // to 2 ^ countOfZero
        int value1 = (1 << countOfZero);
 
        // Considering all 2's
        // and extra elements
        int value2 = (countOfOne * (countOfOne - 1)) / 2;
 
        // Considering all 1's
        // and extra elements
        int value3 = countOfTwo;
 
        // Calculating final answer
        answer = value1 * (value2 + value3);
 
        // Print the answer
        System.out.println(answer);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Initializing an array
        int[] arr = { 2, 0, 1, 2, 1 };
 
        countTotal(arr);
    }
}
 
// This code is contributed by maddler.


Python3
# Python3 program for the above approach
 
# Function to count the total number
# of subsequences with sum S-2
def countTotal(vec) :
 
    # Calculating vector sum using
    # accumulate function
    sum1 = sum(vec);
 
    N = len(vec);
 
    # Answer variable stores count
    # of subsequences with desired sum
    answer = 0;
    countOfZero = 0; countOfOne = 0; countOfTwo = 0;
    for x in vec :
         
        if (x == 0) :
            countOfZero += 1;
             
        elif (x == 1) :
            countOfOne += 1;
             
        elif (x == 2) :
            countOfTwo += 1;
 
    # Select any number of
    # zeroes from 0 to count[0]
    # which is equivalent
    # to 2 ^ countOfZero
    value1 = 2 ** countOfZero;
 
    # Considering all 2's
    # and extra elements
    value2 = (countOfOne * (countOfOne - 1)) // 2;
 
    # Considering all 1's
    # and extra elements
    value3 = countOfTwo;
 
    # Calculating final answer
    answer = value1 * (value2 + value3);
 
    # Print the answer
    print(answer);
 
# Driver Code
if __name__ == "__main__" :
 
    # Initializing a vector
    vec = [ 2, 0, 1, 2, 1 ];
    countTotal(vec);
     
    # This code is contributed by AnkThon


C#
// Above approach implemented in C#
using System;
 
public class GFG {
     
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int[] arr)
    {
 
        int N = arr.Length;
 
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
 
        int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
        for (int i = 0; i < N; i++) {
 
            if (arr[i] == 0)
                countOfZero++;
                 
            else if (arr[i] == 1)
                countOfOne++;
                 
            else if (arr[i] == 2)
                countOfTwo++;
        }
 
        // Select any number of
        // zeroes from 0 to count[0]
        // which is equivalent
        // to 2 ^ countOfZero
        int value1 = (1 << countOfZero);
 
        // Considering all 2's
        // and extra elements
        int value2 = (countOfOne * (countOfOne - 1)) / 2;
 
        // Considering all 1's
        // and extra elements
        int value3 = countOfTwo;
 
        // Calculating final answer
        answer = value1 * (value2 + value3);
 
        // Print the answer
        Console.WriteLine(answer);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
       
        // Initializing an array
        int[] arr = { 2, 0, 1, 2, 1 };
 
        countTotal(arr);
    }
}
 
// This code is contributed by AnkThon


Javascript


输出
6

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

有效方法:这个想法是使用组合数学,除了0's、1's2's之外,我们数组中的所有其他元素都将成为所需子序列的一部分。我们称它们为额外元素。然后,计算数组中0、12 的出现次数。假设0 的计数是x1 的计数是y2 的计数是z

请按照以下步骤解决问题:

  • 将变量sum初始化为数组的总和。
  • 将变量answer初始化为0以存储答案。
  • 初始化变量countOfZero、countOfOnecountOfTwo以存储0、12 的计数。
  • 使用迭代器x遍历数组vec[]并执行以下任务:
    • 计算0、12 的出现次数。
  • 将变量value1初始化为2 countOfZero
  • 将变量value2初始化为(countOfOne * (countOfOne – 1)) / 2
  • 将变量value3初始化为countOfTwo。
  • answer的值设置为value1 * ( value2 + value)。
  • 执行上述步骤后,打印answer的值作为答案。

下面是上述方法的实现。

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the total number
// of subsequences with sum S-2
void countTotal(vector& vec)
{
 
    // Calculating vector sum using
    // accumulate function
    int sum = accumulate(vec.begin(),
                         vec.end(), 0LL);
 
    int N = (int)vec.size();
 
    // Answer variable stores count
    // of subsequences with desired sum
    int answer = 0;
 
    int countOfZero = 0,
        countOfOne = 0,
        countOfTwo = 0;
    for (auto x : vec) {
        if (x == 0)
            countOfZero++;
        else if (x == 1)
            countOfOne++;
        else if (x == 2)
            countOfTwo++;
    }
 
    // Select any number of
    // zeroes from 0 to count[0]
    // which is equivalent
    // to 2 ^ countOfZero
    int value1 = pow(2, countOfZero);
 
    // Considering all 2's
    // and extra elements
    int value2
        = (countOfOne
           * (countOfOne - 1))
          / 2;
 
    // Considering all 1's
    // and extra elements
    int value3 = countOfTwo;
 
    // Calculating final answer
    answer = value1 * (value2 + value3);
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
 
    // Initializing a vector
    vector vec = { 2, 0, 1, 2, 1 };
 
    countTotal(vec);
 
    return 0;
}

Java

/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int[] arr)
    {
 
        int N = arr.length;
 
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
 
        int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
        for (int i = 0; i < N; i++) {
 
            if (arr[i] == 0)
                countOfZero++;
            else if (arr[i] == 1)
                countOfOne++;
            else if (arr[i] == 2)
                countOfTwo++;
        }
 
        // Select any number of
        // zeroes from 0 to count[0]
        // which is equivalent
        // to 2 ^ countOfZero
        int value1 = (1 << countOfZero);
 
        // Considering all 2's
        // and extra elements
        int value2 = (countOfOne * (countOfOne - 1)) / 2;
 
        // Considering all 1's
        // and extra elements
        int value3 = countOfTwo;
 
        // Calculating final answer
        answer = value1 * (value2 + value3);
 
        // Print the answer
        System.out.println(answer);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Initializing an array
        int[] arr = { 2, 0, 1, 2, 1 };
 
        countTotal(arr);
    }
}
 
// This code is contributed by maddler.

Python3

# Python3 program for the above approach
 
# Function to count the total number
# of subsequences with sum S-2
def countTotal(vec) :
 
    # Calculating vector sum using
    # accumulate function
    sum1 = sum(vec);
 
    N = len(vec);
 
    # Answer variable stores count
    # of subsequences with desired sum
    answer = 0;
    countOfZero = 0; countOfOne = 0; countOfTwo = 0;
    for x in vec :
         
        if (x == 0) :
            countOfZero += 1;
             
        elif (x == 1) :
            countOfOne += 1;
             
        elif (x == 2) :
            countOfTwo += 1;
 
    # Select any number of
    # zeroes from 0 to count[0]
    # which is equivalent
    # to 2 ^ countOfZero
    value1 = 2 ** countOfZero;
 
    # Considering all 2's
    # and extra elements
    value2 = (countOfOne * (countOfOne - 1)) // 2;
 
    # Considering all 1's
    # and extra elements
    value3 = countOfTwo;
 
    # Calculating final answer
    answer = value1 * (value2 + value3);
 
    # Print the answer
    print(answer);
 
# Driver Code
if __name__ == "__main__" :
 
    # Initializing a vector
    vec = [ 2, 0, 1, 2, 1 ];
    countTotal(vec);
     
    # This code is contributed by AnkThon

C#

// Above approach implemented in C#
using System;
 
public class GFG {
     
    // Function to count the total number
    // of subsequences with sum S-2
    static void countTotal(int[] arr)
    {
 
        int N = arr.Length;
 
        // Answer variable stores count
        // of subsequences with desired sum
        int answer = 0;
 
        int countOfZero = 0, countOfOne = 0, countOfTwo = 0;
        for (int i = 0; i < N; i++) {
 
            if (arr[i] == 0)
                countOfZero++;
                 
            else if (arr[i] == 1)
                countOfOne++;
                 
            else if (arr[i] == 2)
                countOfTwo++;
        }
 
        // Select any number of
        // zeroes from 0 to count[0]
        // which is equivalent
        // to 2 ^ countOfZero
        int value1 = (1 << countOfZero);
 
        // Considering all 2's
        // and extra elements
        int value2 = (countOfOne * (countOfOne - 1)) / 2;
 
        // Considering all 1's
        // and extra elements
        int value3 = countOfTwo;
 
        // Calculating final answer
        answer = value1 * (value2 + value3);
 
        // Print the answer
        Console.WriteLine(answer);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
       
        // Initializing an array
        int[] arr = { 2, 0, 1, 2, 1 };
 
        countTotal(arr);
    }
}
 
// This code is contributed by AnkThon

Javascript


输出
6

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