昨天,一个群里的网友,问了这么个问题:
从1到19共19个整数,请打印出利用这19个整数任意多个相加结果等于20的所有可能性。例如:
1+19;
1+2+17;
1+2+3+14;
1+2+3+4+10;
.
.
.
3+4+6+7;
3+5+12;
.
.
但是如同19+1和1+19是一样的,作为一个算式
我想了出来一个解决办法,但是,还没有进行算式过滤。先贴出来,供大家讨论。
package com.demo;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Frank email:zhufeng1981_888@hotmail.com
* @since 1.0
*
*/
public class Expression {
static int[] NUM = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19 };
/**
*
* @param num the array of 0 to 19
* @param addend the first add number
* @return list of expressions
*/
public static List<String> contains(int[] num, int addend) {
StringBuilder sb = new StringBuilder(addend + "+");
List<String> results = new ArrayList<String>();
int temp;
for (int i = 0; i < NUM.length; i++) {
temp = 20 - addend;
for (int j = i; j < NUM.length; j++) {
if (temp - NUM[j] > 0) {
sb.append(NUM[j] + "+");
temp = temp - NUM[j];
} else if (temp - NUM[j] == 0) {
sb.append(NUM[j] + "");
temp = temp - NUM[j];
results.add(sb.toString());
sb = new StringBuilder(addend + "+");
break;
} else {
if (j < NUM.length)
sb = new StringBuilder(addend + "+");
continue;
}
}
}
return results;
}
public static void showNoneRepeatExpression() {
List<String> allExpressions = new ArrayList<String>();
for (int j = 0; j < NUM.length; j++) {
List<String> list = Expression.contains(NUM, NUM[j]);
allExpressions.addAll(list);
}
for (int i = 0; i < allExpressions.size(); i++) {
System.out.println(allExpressions.get(i));
}
}
public static List<String> filterHandler(List<String> list) {
int n = list.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
}
}
return list;
}
public static void main(String[] args) {
showNoneRepeatExpression();
}
}