2016-09-29 56 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

相關問題