假设我有一排数字“ 1 2 3 4”
我需要获取所有可能的值
1+2+3+4
1+2+3-4
1+2-3+4
1+2-3-4
...
-1-2-3-4
试图写一个递归
但它可以与“ 1 2”和“ 1 2 3”一起使用
它应该与1 2 3 ... n
checkSum(0, list.size(), list);
private void checkSum(int start, int end, List<Long> list) {
for (int i = start; i < end; i++){
list.set(i, list.get(i) * (-1L));
printLine(list);
checkSum(i+2, end, list);
}
}
private void printLine(List<Long> list) {
for (int i = 0; i < list.size(); i++) {
if (i > 0)
if (list.get(i) > 0L)
System.out.print("+");
System.out.print(String.valueOf(list.get(i)));
}
System.out.println();
}
最佳答案
下面的十亿个方法之一...
public class Thingy {
public static void main(String[] args) {
printAll(0, 0, Arrays.asList(1L, 2L, 3L, 4L), "TEST1> ");
printAll(0, 0, Arrays.asList(5L, 6L, 3L, 8L, 9L), "TEST2> ");
}
private static void printAll(int i, long accumulator, List<Long> source, String output) {
if(i >= source.size()) {
System.out.println(output + " = " + accumulator);
} else {
long n = source.get(i);
printAll(i + 1, accumulator + n, source, output + " + " + n);
printAll(i + 1, accumulator - n, source, output + " - " + n);
}
}
}
输出...
TEST1> + 1 + 2 + 3 + 4 = 10
TEST1> + 1 + 2 + 3 - 4 = 2
TEST1> + 1 + 2 - 3 + 4 = 4
TEST1> + 1 + 2 - 3 - 4 = -4
TEST1> + 1 - 2 + 3 + 4 = 6
TEST1> + 1 - 2 + 3 - 4 = -2
TEST1> + 1 - 2 - 3 + 4 = 0
TEST1> + 1 - 2 - 3 - 4 = -8
TEST1> - 1 + 2 + 3 + 4 = 8
TEST1> - 1 + 2 + 3 - 4 = 0
TEST1> - 1 + 2 - 3 + 4 = 2
TEST1> - 1 + 2 - 3 - 4 = -6
TEST1> - 1 - 2 + 3 + 4 = 4
TEST1> - 1 - 2 + 3 - 4 = -4
TEST1> - 1 - 2 - 3 + 4 = -2
TEST1> - 1 - 2 - 3 - 4 = -10
TEST2> + 5 + 6 + 3 + 8 + 9 = 31
TEST2> + 5 + 6 + 3 + 8 - 9 = 13
TEST2> + 5 + 6 + 3 - 8 + 9 = 15
TEST2> + 5 + 6 + 3 - 8 - 9 = -3
TEST2> + 5 + 6 - 3 + 8 + 9 = 25
TEST2> + 5 + 6 - 3 + 8 - 9 = 7
TEST2> + 5 + 6 - 3 - 8 + 9 = 9
TEST2> + 5 + 6 - 3 - 8 - 9 = -9
TEST2> + 5 - 6 + 3 + 8 + 9 = 19
TEST2> + 5 - 6 + 3 + 8 - 9 = 1
TEST2> + 5 - 6 + 3 - 8 + 9 = 3
TEST2> + 5 - 6 + 3 - 8 - 9 = -15
TEST2> + 5 - 6 - 3 + 8 + 9 = 13
TEST2> + 5 - 6 - 3 + 8 - 9 = -5
TEST2> + 5 - 6 - 3 - 8 + 9 = -3
TEST2> + 5 - 6 - 3 - 8 - 9 = -21
TEST2> - 5 + 6 + 3 + 8 + 9 = 21
TEST2> - 5 + 6 + 3 + 8 - 9 = 3
TEST2> - 5 + 6 + 3 - 8 + 9 = 5
TEST2> - 5 + 6 + 3 - 8 - 9 = -13
TEST2> - 5 + 6 - 3 + 8 + 9 = 15
TEST2> - 5 + 6 - 3 + 8 - 9 = -3
TEST2> - 5 + 6 - 3 - 8 + 9 = -1
TEST2> - 5 + 6 - 3 - 8 - 9 = -19
TEST2> - 5 - 6 + 3 + 8 + 9 = 9
TEST2> - 5 - 6 + 3 + 8 - 9 = -9
TEST2> - 5 - 6 + 3 - 8 + 9 = -7
TEST2> - 5 - 6 + 3 - 8 - 9 = -25
TEST2> - 5 - 6 - 3 + 8 + 9 = 3
TEST2> - 5 - 6 - 3 + 8 - 9 = -15
TEST2> - 5 - 6 - 3 - 8 + 9 = -13
TEST2> - 5 - 6 - 3 - 8 - 9 = -31
关于java - java获取所有可能的变体(正数和负数),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33149453/