Java 如何统计所有可能的病例?
例如,我有一个长度为n=3的数组:Java 如何统计所有可能的病例?,java,algorithm,Java,Algorithm,例如,我有一个长度为n=3的数组: for(int i = 0; i < n; i++) { array[i] = i; } 因此,对于n=3,病例数应为7。 在我的代码中: int n = 3; int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = i; } int sum = 0; for (int i = 0; i < n; i++) { System.out.pr
for(int i = 0; i < n; i++) {
array[i] = i;
}
因此,对于n=3,病例数应为7。
在我的代码中:
int n = 3;
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.println(array[i] + " ");
sum++;
for (int j = i; j < n; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
sum++;
}
System.out.println("sum = " + sum);
数字2是两倍,所以它是错误的,总和实际上等于5。而且我也没有收到任何案例
4. 0 1
and
5. 0 2
如何统计所有可能的案例?集合,而不是数组
第一个重要的注意事项是,这里使用的不是固定长度的数组,而是不同长度的集合
看看你的例子。你允许
0
1
2
0, 1
0, 2
1, 2
并非所有尺寸均为3
你也不区分
0, 1
1, 0
所以顺序并不重要,就像在集合中一样
发电机组 这就是你在这里描述的原因。对于示例集
{0,1,2}
,其幂集定义为
P({0, 1, 2}) = {
{}, // empty set
{0},
{1},
{2},
{0, 1},
{0, 2},
{1, 2},
{0, 1, 2}
}
幸运的是,对于它们的大小,存在一个简单的闭合公式。如果n
是输入集的大小,则电源集的大小为
2^n
但它们也会计算空集,因此如果您不想这样做,则需要-1
:
2^n - 1
解决方案 因此,可以用Java编写
int Set<Integer> input = ...
int size = (int) Math.pow(2, input.size()) - 1;
int集输入=。。。
int size=(int)Math.pow(2,input.size())-1;
仅此而已,您不需要手动构建内容
但是,如果你很好奇,想建立它们,看看下面的问题。这是维基百科上显示的递归公式的实现
因此,完全没有效率,但也在工作:
int Set<Integer> input = ...
// Build the power-set using the method from linked question
Set<Set<Integer>> power = powerSet(input);
int size = power.size() - 1;
int集输入=。。。
//使用链接问题的方法构建幂集
设置功率=功率集(输入);
int size=power.size()-1;
Math.pow(2,n)-1?看起来像a。为什么投票失败?问题很清楚,包含一个示例、所需输出和当前输出。OP也展示了自己的努力,首先她自己尝试了,她也向我们展示了代码。我觉得不错。如果她不知道“功率集”这个词,那么问题本身也不是那么容易解决的。
int Set<Integer> input = ...
int size = (int) Math.pow(2, input.size()) - 1;
int Set<Integer> input = ...
// Build the power-set using the method from linked question
Set<Set<Integer>> power = powerSet(input);
int size = power.size() - 1;