Write a function in Java. The function is as follows: Any given set of numbers, such as {12,60,-8,99,15,35,17,18}, to find out the result of the addition of any number 35 (arbitrary set).
can be recursive algorithm to solve:
Package test1;
Import Java.util.Arrays; public class Demo {public static void main (string[] args) {String str = ' 12,60,-8,99,15,35,17,18,8,
10,11,12 ";
int sum = 35;
Diguisum (str,sum);
public static void Diguisum (String str,int sum) {string[] x = Str.split (",");
int[] Array = arraytransform (x);
for (int i = 0; i < Array.Length i++) {int[] cache = new Int[i + 1];
int ceng =-1;
int cengquit = i;
int startpiont = 0;
Cir (CEng, cengquit, Startpiont, array, cache, sum); }///recursive results public static void Cir (int ceng, int cengquit, int startpiont, int[] array, int[] cache, int
sum) {ceng++;
for (int i = Startpiont i < array.length; i++) {Cache[ceng] = Array[i];
if (CEng = = Cengquit) {if (getsum (cache) = sum) {Printcache (cache); } if (Getsum (cache) > sum) {break;
} if (CEng < cengquit) {Startpiont = i + 1;
Cir (CEng, cengquit, Startpiont, array, cache,sum);
}}//Get combined number and public static int getsum (int[] cache) {int sum = 0;
for (int i = 0; i < cache.length i++) {sum = sum + cache[i];
return sum;
The possible public static void Printcache (int[] cache) of the//print combination is {for (int i = 0; i < cache.length; i++) {
System.out.print (Cache[i] + ",");
} System.out.println ();
}//convert array type and prepare for increased efficiency public static int[] Arraytransform (string[] strarray) {int length = 0;
int[] array = new Int[strarray.length];
for (int i = 0; i < strarray.length i++) {Array[i] = integer.valueof (strarray[i));
} Arrays.sort (array);
for (int i = 0; i < Array.Length i++) {if (Array[i] >) {length = i;
Break
} int[] Dest = new Int[length];
System.arraycopy (array, 0, dest, 0, length);
return dest; }
}
This algorithm is suitable for reference.
Run Result:
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/