An array of integer a[] = {3, 5, 7}
//数组元素是唯一的
打印所有产品组合:
输入:
3, 5, 7
输出:
3, 5, 7, 15, 21, 35, 105
最近我在面试中被问到这个问题。我想不出办法。请提出方法/代码。
最佳答案
你可以用一个简单的递归函数来做到这一点:
def all_products(S,A,base=1):
"""Add all products of base times elements from the array A to set S"""
S.add(base)
if A:
all_products(S,A[1:],base)
all_products(S,A[1:],base*A[0])
S=set()
all_products(S, [3, 5, 7])
print sorted(S)
此方法还包括不将任何元素相乘的结果 (1)。
关于algorithm - 打印数组的所有产品组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26815931/