import java.util.ArrayList;
import java.util.Arrays;
public class ncsmsoft {
public static void main(String[] args) {
//test result
System.out.print(findSum(35, "12,60,8,-8,99,15,35,17,18"));
}
/*==============================================
function:findSum
creator:(name)
create time:(time)
updator name:(name)
update time:(time)
version number:1.0
description:find all the possible assembled from the character string that the sum of which
equal to the appoint value
input parameter:Double he //appoint value
String shuzu //a character string divide by comma
output parameter:result
output format:for example "12+8+15;35;17+18"
testor :(name)
=================================================*/
private static String findSum(double he, String shuzu) {
StringBuffer result = new StringBuffer();
//Please input your program here without changing of the other code
String[] strs = shuzu.split(",");
int[] shuzuInt = new int[strs.length];
for (int i = 0; i < shuzuInt.length; i++) {
shuzuInt[i] = Integer.parseInt(strs[i]);
}
Arrays.sort(shuzuInt); // 对初始数据进行排序,便于算法的实现
ArrayList<Integer> okList = new ArrayList<Integer>(); //存放的是当前找到的合法的元素,这些元素的和小于SUM
find(shuzuInt, he, 0, okList, result); //通过递归的方式进行查找
//return your result as the format "12+8+15;35;17+18"
return result.toString();
}
private static void find(int[] a, final double sum, int cur,
ArrayList<Integer> okList, StringBuffer result) {
int beg = okList.size() == 0 ? 0 : okList.get(okList.size() - 1) + 1; // 当前元素的查找范围的起始位置
for (int i = beg; i < a.length; i++) { // 从起始位置到结束位置,查找合适的元素
cur += a[i]; // 在前面元素的和的基础上,加上当前元素
if (cur < sum) { // 如果仍然小于SUM,证明当前元素(第n+1个)合法,继续寻找第n+2个元素
okList.add(i);
find(a, sum, cur, okList, result);
cur -= a[i]; // 消除第i个元素的影响,为了试验第i+1个元素做准备
okList.remove(okList.size() - 1); // 消除第i个元素的影响,为了试验第i+1个元素做准备
} else if (cur == sum) {
for (int x : okList) { // 构造表达式,并存入result
result.append(a[x]);
result.append("+");
}
result.append(a[i]);
result.append(";");
break; // 返回到上一个状态
} else { // 如果大于SUM,也返回到上一个状态
break;
}
}
}
private String findAll(int sum, int[] elements,StringBuffer result){
for(int i=0; i<elements.length; i++){
if(elements[i]==sum){
result.append(elements[i]);
}
if()
}
return null;
}
}