给定目标产品号,从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
给定目标产品号,从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
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();
}
}
有趣的问题。你的编码尝试解决这个问题是什么样的? –
与Stack..but一起使用它,但当它进入更多的元素,并让我与ArrayIndexOutOfBounds异常卡住了。 – ARP
@ARP如果你发布你的代码,人们可以帮助你。 –