java子集数
class Solution {
int f(int[] a, int s, int n) {
if (n == 0)
return s;
return f(a, s + 1, n - 1) + f(a, s, n - 1);
}
}
class Test {
public static void main(String[] args) {
int[] a = { 1, 1, 2, 3 };
System.out.println(new Solution().f(a, 0, a.length));
}
}
我写了一个代码来打印子集的数量,在每个索引中,我有两个选择,是否将a[I]包含在子集中,因为每当要包含元素时,我会向s添加1,但这种方法给出了错误的答案。为什么是错的
# 1 楼答案
这是显而易见的解决办法。但如果你真的想这样找到它,它应该“返回1”而不是“返回s”,因为每次它都到达零,这意味着没有留下任何元素,因此列表为空,因此为1