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;
}
}