2014-11-08 157 views
1

的所有产品组合整数的数组a[] = {3, 5, 7} //数组元素是唯一
打印所有产品组合:打印阵列

input : 3,5,7
output: 3,5,7,15,21, 35,105

最近我在面试中被问到这个问题。我无法想到办法。请建议方法/代码。

+0

运行的版本是否有任何要求,以检查结果的重复?像2,3,6,7会有重复,因为2 * 3 * 7 = 6 * 7 – 2014-11-08 10:33:20

+0

一般来说,您在这里有2^n个产品(每个元素可以存在或不存在),但检查重复是 – 2014-11-08 10:35:34

+0

使用的另一件事递归... – 2014-11-08 10:42:13

回答

2

可以用一个简单的递归函数做到这一点:

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)。

+0

我喜欢S.add关心产品独特性的方式。对Python很好。 – 2014-11-08 11:51:24

1

这里是Java代码创建集,你想:

import java.util.*; 

public class MainClass { 

    public static void main(String[] args) throws java.lang.Exception { 
     MainClass mainClass = new MainClass(); 
     Set<Integer> ints = new HashSet<Integer>(); 

     ints.add(3); 
     ints.add(5); 
     ints.add(7); 

     ints = mainClass.recursiveSetCreator(ints); 

     printOutput(ints); 
    } 

    private static void printOutput(Set<Integer> ints) { 
     List list = new ArrayList(ints); 
     Collections.sort(list); 
     System.out.println(list); 
    } 

    public Set<Integer> recursiveSetCreator(Set<Integer> recInput) { 
     if (recInput.size() == 1) { 
      return recInput; 
     } 
     List integerList = new ArrayList(recInput); 
     Integer lastItem = (Integer) integerList.remove(integerList.size() - 1); 
     recInput.remove(lastItem); 
     recInput = recursiveSetCreator(recInput); 
     int size = recInput.size(); 
     integerList = new ArrayList(recInput); 
     for (int i = 0; i < size; i++) { 
      Integer item = (Integer) integerList.get(i); 
      recInput.add(item * lastItem); 
     } 
     recInput.add(lastItem); 
     return recInput; 
    } 
} 

你可以看到Ideone