入参1:int[ ] value = {2, 3, 1, 3 ... ...}
入参2:int N
返回:当N=2时,返回 Sn = 2*3 + 2*1 + 2*3 ... ...+ 3*1 + 3*3 ... ... + 1*3 .. ...
当N=3时,返回 Sn = 2*3*1 + 2*3*3 ... ...+ 2 * 1 * 3... ... + 3 *1 * 3 ... ...
当N....时 ......
------解决方案--------------------
public class Test {
public static int func(int[] value, int n) {
int result = 0;
if (value.length < n) {
return 0;
} else {
for (int i = 0; i <= value.length - n; i++) {
int temp = 1;
for (int j = 0; j < n; j++) {
temp *= value[i + j];
}
result += temp;
}
}
return result;
}
public static void main(String[] args) {
int[] value = { 2, 3, 1, 3 };
int n = 2;
System.out.println(func(value, n));
}
}
我没有考虑溢出问题,如果实际实用,数据量比较大的话,需要考虑溢出问题。
------解决方案--------------------
public class Test {
private static int result;
public static void main(String[] args) {
int[] set = {2, 3, 1, 3};
int n = 4;
for (int k = 2; k <= n; k++) {
result = 0;
int[] subset = new int[k];
calc(set, subset, set.length, k);
System.out.printf("k = %d, Sn = %d%n", k, result);
}
}
public static void calc(int[] set, int[] subset, int n, int k) {
if (k == 0) {
int t = 1;
for (int i = 0; i < subset.length; i++) {
t *= subset[i];
}
result += t;
return;
}
for (int i = n; i >= k; i--) {
subset[k - 1] = set[i - 1];
calc(set, subset, i - 1, k - 1);
}
}
}
输出
k = 2, Sn = 29
k = 3, Sn = 39
k = 4, Sn = 18