You can consider the table as a list of values. Then, if you have N tables, your task is to find lists of N integers (each taken from one of N tables), the product of which is equal to p. You can solve the problem recursively:
- given a non-empty list of tables
{t1, t2, t3, ...} p,v t1 p / v {t2, t3, ...} ( , p % v == 0,- .
java:
public class SO6026472 {
public static void main(String[] args) {
Integer[] t1 = new Integer[] {2,-2,4,7};
Integer[] t2 = new Integer[] {3,-3,-8,0};
Integer[] t3 = new Integer[] {-1,-4,-7,6};
Integer[] t4 = new Integer[] {1,5};
List<List<Integer>> tables = new ArrayList<List<Integer>>();
tables.add(Arrays.asList(t1));
tables.add(Arrays.asList(t2));
tables.add(Arrays.asList(t3));
tables.add(Arrays.asList(t4));
SO6026472 c = new SO6026472();
List<List<Integer>> solutions = c.find(36, tables);
for (List<Integer> solution : solutions) {
System.out.println(
Arrays.toString(solution.toArray(new Integer[0])));
}
}
public List<List<Integer>> find(int p, List<List<Integer>> tables) {
List<List<Integer>> solutions = new ArrayList<List<Integer>>();
if (tables.size() == 0)
return solutions;
if (tables.size() == 1) {
if (tables.get(0).contains(p)) {
List<Integer> solution = new ArrayList<Integer>();
solution.add(p);
solutions.add(solution);
return solutions;
} else
return solutions;
}
List<Integer> table = tables.remove(0);
for (Integer value : table) {
if (value != 0 && p % value == 0) {
List<List<Integer>> subSolutions = find(p / value, tables);
if (! subSolutions.isEmpty()) {
for (List<Integer> subSolution : subSolutions) {
subSolution.add(0, value);
}
solutions.addAll(subSolutions);
}
}
}
tables.add(0, table);
return solutions;
}
}
:
[2, 3, 6, 1]
[-2, -3, 6, 1]
. , , memoization . , .