【发布时间】:2018-10-02 16:09:17
【问题描述】:
final class Combination {
public static void findCombinations(String[][] sets) {
int combinations = 1;
for(int i = 0; i < sets.length; combinations *= sets[i].length, i++);
for(int i = 0; i < combinations; i++) {
int j = 1;
for(String[] set : sets) {
System.out.print(set[(i/j)%set.length] + " ");
j *= set.length;
}
System.out.println();
}
}
public static void main(String[] args) {
findCombinations(new String[][]{{"a","b","c"}, {"d","e","i"}, {"f","g","h"}});
}
}
我的答案是这样的
a d f
b d f
c d f
a e f
b e f
c e f
a i f
b i f
c i f
a d g
b d g
c d g
a e g
b e g
c e g
a i g
b i g
c i g
a d h
b d h
c d h
a e h
b e h
c e h
a i h
b i h
c i h
我想知道我的解决方案的时间复杂度以及是否有任何方法可以改进解决方案。
【问题讨论】:
-
我认识的许多人都认为将
combinations *= sets[i].length移动到循环主体而不是将其放在头部中会更好。 -
@ReazMurshed 对于 n 的任何合理定义,复杂度绝对是 not O(n^2)。这是指数级的。
-
我知道已经一年多了,但你可能想看看 Guava 的实现:guava.dev/releases/22.0/api/docs/com/google/common/collect/…
标签: java performance time-complexity cartesian-product