📜  仅使用数组元素来计算目标数的方法数

📅  最后修改于: 2021-05-04 18:24:55             🧑  作者: Mango

给定一个整数数组,请查找仅使用数组元素和加法或减法运算符来计算目标数的多种方法。

例子:

Input: arr[] = {-3, 1, 3, 5}, k = 6
Output: 4
Explanation - 
- (-3) + (3)
+ (1) + (5)
+ (-3) + (1) + (3) + (5)
- (-3) + (1) - (3) + (5)

Input: arr[] = {2, 3, -4, 4}, k = 5
Output: 6
Explanation - 
+ (2) + (3)
+ (2) + (3) + (4) + (-4)
+ (2) + (3) - (4) - (-4)
- (3) + (4) - (-4)
- (2) + (3) + (4)
- (2) + (3) - (-4)

该问题类似于0-1背包问题,其中对于每个项目,我们要么选择完整项目,要么根本不选择(0-1属性)。这里的想法保持不变,即我们要么包含当前数字,要么忽略它。如果包含当前数字,则将其从剩余目标中减去或相加,然后递归以获取具有新目标的剩余数字。如果目标达到0,我们将增加计数。如果我们已经处理了数组的所有元素并且未达到目标,则计数保持不变。

下面是上述想法的递归实现。

C++
// C++ program to find the number of ways to calculate
// a target number using only array elements and
// addition or subtraction operator.
#include 
#include 
using namespace std;
  
// Function to find the number of ways to calculate
// a target number using only array elements and
// addition or subtraction operator.
int findTotalWays(vector arr, int i, int k)
{
  
    // If target is reached, return 1
    if (k == 0 && i == arr.size())
        return 1;
  
    // If all elements are processed and
    // target is not reached, return 0
    if (i >= arr.size())
        return 0;
  
    // Return total count of three cases
    // 1. Don't consider current element
    // 2. Consider current element and subtract it from target
    // 3. Consider current element and add it to target
    return findTotalWays(arr, i + 1, k)
           + findTotalWays(arr, i + 1, k - arr[i])
           + findTotalWays(arr, i + 1, k + arr[i]);
}
  
// Driver Program
int main()
{
    vector arr = { -3, 1, 3, 5, 7 };
  
    // target number
    int k = 6;
  
    cout << findTotalWays(arr, 0, k) << endl;
  
    return 0;
}


Java
// Java program to find the number
// of ways to calculate a target
// number using only array elements and
// addition or subtraction operator.
import java.util.*;
  
class GFG {
  
    // Function to find the number of ways to calculate
    // a target number using only array elements and
    // addition or subtraction operator.
    static int findTotalWays(Vector arr, int i, int k)
    {
  
        // If target is reached, return 1
        if (k == 0 && i == arr.size()) {
            return 1;
        }
  
        // If all elements are processed and
        // target is not reached, return 0
        if (i >= arr.size()) {
            return 0;
        }
  
        // Return total count of three cases
        // 1. Don't consider current element
        // 2. Consider current element and subtract it from target
        // 3. Consider current element and add it to target
        return findTotalWays(arr, i + 1, k)
            + findTotalWays(arr, i + 1, k - arr.get(i))
            + findTotalWays(arr, i + 1, k + arr.get(i));
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { -3, 1, 3, 5 };
        Vector v = new Vector();
        for (int a : arr) {
            v.add(a);
        }
  
        // target number
        int k = 6;
  
        System.out.println(findTotalWays(v, 0, k));
    }
}
  
// This code contributed by Rajput-Ji


Python3
# Python 3 program to find the number of 
# ways to calculate a target number using 
# only array elements and addition or 
# subtraction operator.
  
# Function to find the number of ways to 
# calculate a target number using only 
# array elements and addition or 
# subtraction operator.
def findTotalWays(arr, i, k):
  
    # If target is reached, return 1
    if (k == 0 and i == len(arr)):
        return 1    
  
    # If all elements are processed and
    # target is not reached, return 0
    if (i >= len(arr)):
        return 0
  
    # Return total count of three cases
    # 1. Don't consider current element
    # 2. Consider current element and 
    # subtract it from target
    # 3. Consider current element and
    # add it to target
    return (findTotalWays(arr, i + 1, k) + 
            findTotalWays(arr, i + 1, k - arr[i]) + 
            findTotalWays(arr, i + 1, k + arr[i]))
  
# Driver Code
if __name__ == '__main__':
    arr = [-3, 1, 3, 5, 7]
  
    # target number
    k = 6
  
    print(findTotalWays(arr, 0, k))
      
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to find the number
// of ways to calculate a target
// number using only array elements and
// addition or subtraction operator.
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Function to find the number of ways to calculate
    // a target number using only array elements and
    // addition or subtraction operator.
    static int findTotalWays(List arr, int i, int k)
    {
        // If target is reached, return 1
        if (k == 0 && i ==  arr.Count) {
            return 1;
        }
  
        // If all elements are processed and
        // target is not reached, return 0
        if (i >= arr.Count) {
            return 0;
        }
  
        // Return total count of three cases
        // 1. Don't consider current element
        // 2. Consider current element and subtract it from target
        // 3. Consider current element and add it to target
        return findTotalWays(arr, i + 1, k)
            + findTotalWays(arr, i + 1, k - arr[i])
            + findTotalWays(arr, i + 1, k + arr[i]);
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { -3, 1, 3, 5, 7 };
        List v = new List();
        foreach(int a in arr)
        {
            v.Add(a);
        }
  
        // target number
        int k = 6;
  
        Console.WriteLine(findTotalWays(v, 0, k));
    }
}
  
// This code has been contributed by 29AjayKumar


输出 :

10

上述解决方案的时间复杂度为O(3 ^ n),即指数。