Get All Possible Products
//Input: [3, 5, 11] (prime numbers)
//Output: [3, 5, 11, 15, 33, 55, 165] (all possible product)
public class GetAllProducts {
public List<Integer> getAllPossibleProducts(int[] primes) {
List<Integer> result = new ArrayList<Integer>();
if(primes == null || primes.length == 0) {
return result;
}
for(int i=0; i<primes.length; i++) {
int len = result.size();
result.add(primes[i]);
for(int j=0; j<len; j++) {
result.add(result.get(j) * primes[i]);
}
}
Collections.sort(result);
return result;
}
// method 2:
public List<Integer> getAllPossibleProducts2(int[] primes) {
List<Integer> result = new ArrayList<Integer>();
if(primes == null || primes.length == 0) {
return result;
}
int len = primes.length;
dfs(result, primes, 1, new boolean[len]);
result.remove(0);
Collections.sort(result);
return result;
}
public void dfs(List<Integer> result, int[] primes, int product, boolean[] used) {
if(!result.contains(product)) {
result.add(product);
}
for(int i=0; i<primes.length; i++) {
if(!used[i]) {
used[i] = true;
product *= primes[i];
dfs(result, primes, product, used);
product /= primes[i];
used[i] = false;
}
}
}
}
//Input: [3, 5, 11] (prime numbers)
//Output: [3, 5, 11, 15, 33, 55, 165] (all possible product)
public class GetAllProducts {
public List<Integer> getAllPossibleProducts(int[] primes) {
List<Integer> result = new ArrayList<Integer>();
if(primes == null || primes.length == 0) {
return result;
}
for(int i=0; i<primes.length; i++) {
int len = result.size();
result.add(primes[i]);
for(int j=0; j<len; j++) {
result.add(result.get(j) * primes[i]);
}
}
Collections.sort(result);
return result;
}
// method 2:
public List<Integer> getAllPossibleProducts2(int[] primes) {
List<Integer> result = new ArrayList<Integer>();
if(primes == null || primes.length == 0) {
return result;
}
int len = primes.length;
dfs(result, primes, 1, new boolean[len]);
result.remove(0);
Collections.sort(result);
return result;
}
public void dfs(List<Integer> result, int[] primes, int product, boolean[] used) {
if(!result.contains(product)) {
result.add(product);
}
for(int i=0; i<primes.length; i++) {
if(!used[i]) {
used[i] = true;
product *= primes[i];
dfs(result, primes, product, used);
product /= primes[i];
used[i] = false;
}
}
}
}