📌  相关文章
📜  通过插入加法运算符可能的数字字符串的所有可能表达式的总和

📅  最后修改于: 2021-04-29 11:11:03             🧑  作者: Mango

给定长度为N的数字字符串str ,任务是通过在字符串的字符之间插入“ +”运算符任意次来查找所有可能表达式的总和。

例子:

方法:想法是以各种可能的方式在字符串的所有可能的索引处插入“ +”运算符并计算总和。最后,打印获得的总和。请按照以下步骤解决问题:

  • 通过在字符串的所有可能的索引处插入‘+’运算符,初始化变量sumOfExp来存储所有可能的表达式的总和。
  • 迭代生成字符串索引的所有可能子集。对于索引的每个子集,在子集的元素处插入“ +”运算符,然后将sumOfExp增加当前表达式的总和。
  • 最后,打印sumOfExp的值。

下面是上述方法的实现:

Python3
# Python program to implement
# the above approach
  
# Function to find sum of all expressions by
# inserting '+' operator at all possible indices
def findSumOfExpressions(S, N):
  
    # Stores sum of all expressions by inserting
    # '+' operator at all possible indices
    sumOfExp = 0
  
    # Generate all possible subset
    # of indices iteratively
    for i in range(2 ** (N - 1)):
  
        # Stores sum of 
        # current expressions
        ans_sub = 0
  
        # Stores numbers of
        # current expressions
        subst = S[0]
  
        # Traverse the string at insert + at
        # current subset of indices
        for j in range(N - 1):
  
            # If current index exists
            # in the current subset
            if (i >> j) & 1:
  
                # Update ans_sub
                ans_sub += int(subst)
  
                # Update subst
                subst = S[j + 1]
            else:
  
                # Update subst
                subst += S[j + 1]
  
            # + can't be inserted after
            # the last index    
            if j == N - 2:
                ans_sub += int(subst)
  
        # Update ans
        sumOfExp += ans_sub
  
    # Base case     
    if N == 1:
        print(int(S))
    else:
  
        # Print answer
        print(sumOfExp)
  
# Driver Code
if __name__ == '__main__':
      
    # Given string
    S = "9999999999"
      
    # Length of the string
    N = len(S)
  
    # Function call
    findSumOfExpressions(S, N)


输出:
12656242944

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