用JAVA寫一個函數。功能如下:任意給定一組數,例如{12,60,-8,99,15,35,17,18},找出任意數相加之後的結果為35(任意設定)的情況.
可以遞歸算法來解:
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); } } // 遞歸求結果 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); } } } // 獲取組合數字之和 public static int getSum(int[] cache) { int sum = 0; for (int i = 0; i < cache.length; i++) { sum = sum + cache[i]; } return sum; } // 打印組合的可能 public static void printcache(int[] cache) { for (int i = 0; i < cache.length; i++) { System.out.print(cache[i] + ","); } System.out.println(); } // 轉換數組類型 且為提高效率做准備 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] > 35) { length = i; break; } } int[] dest = new int[length]; System.arraycopy(array, 0, dest, 0, length); return dest; } }
此算法有做適當參考。
運行結果:
查看本欄目