2016-09-29 58 views
-1

给定目标产品号,从int数组中填充产品与目标产品相同的所有子集。查找产品等于给定目标的int数组的所有子集

例如:

Target product is 12. 

An int array is { 1, 3, 1, 2, 2, 1,2,4 }. 

Then all satisfied subsets whose product is 12 are as follows: 

12 = 1*3*1*2*2 
12 = 3*2*2*1*1*1 
12 = 4*3*1*1*1 
+1

有趣的问题。你的编码尝试解决这个问题是什么样的? –

+0

与Stack..but一起使用它,但当它进入更多的元素,并让我与ArrayIndexOutOfBounds异常卡住了。 – ARP

+0

@ARP如果你发布你的代码,人们可以帮助你。 –

回答

0
public class Subset { 
public static int PROD = 12; 

public static void main(String[] args) { 
    int arr[] = { 1, 3, 1, 2, 2, 1, 2, 4 }; 
    boolean visited[] = new boolean[arr.length]; 
    function(arr, 0, 1, visited); 

} 

public static void function(int a[], int index, int prod, boolean visited[]) { 
    if (prod == PROD) { 
     print(a, visited); 
    } 
    if (index > a.length - 1) 
     return; 
    function(a, index + 1, prod, visited); 
    visited[index] = true; 
    function(a, index + 1, prod * a[index], visited); 
    visited[index] = false; 
} 

private static void print(int[] a, boolean[] visited) { 

    for (int i = 0; i < a.length; i++) { 
     if (visited[i] == true) { 
      System.out.print(a[i] + " "); 
     } 

    } 
    System.out.println(); 
} 

}

+0

由于数组在数组中重复,您将重复SubSets。 – Raman

+0

没有递归,没有没有。循环..但最终结果我得到的是异常。 我不能实现这个没有递归和较少没有。循环? – ARP

+0

你有什么异常? Algo可以通过多种方式解决。我正在执行背包以符合标准。 – Raman

相关问题