求數組中和爲給定數的所有組合

import java.util.Arrays;

public class Test {
	public static void main(String[] args) {
		String str = "6,2,7,3,8,1,9,4";
		double sum = 12;
		diguiSum(str, sum);
	}

	public static void diguiSum(String str, double sum) {
		String[] x = str.split(",");
		double[] array = arrayTransform(x);
		for (int i = 0; i < 100; i++) {
			double[] cache = new double[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,
			double[] array, double[] cache, double 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 double getSum(double[] cache) {
		double sum = 0;
		for (int i = 0; i < cache.length; i++) {
			sum = sum + cache[i];
		}
		return sum;
	}

	// 打印組合的可能
	public static void printcache(double[] cache) {
		for (int i = 0; i < cache.length; i++) {
			System.out.print(cache[i] + ",");
		}
		System.out.println();
	}

	// 轉換數組類型 且爲提高效率做準備
	public static double[] arrayTransform(String[] strArray) {
		int length = 0;

		double[] array = new double[strArray.length];
		for (int i = 0; i < strArray.length; i++) {
			array[i] = Double.valueOf(strArray[i]);
		}
		Arrays.sort(array);
		for (int i = 0; i < array.length; i++) {
			if (array[i] > 100) {
				length = i;
				break;
			}
		}
		double[] dest = new double[length];
		if (length == 0) {
			return array;
		}
		System.arraycopy(array, 0, dest, 0, length);
		return dest;
	}
}

輸出結果爲:

3.0,9.0,
4.0,8.0,
1.0,2.0,9.0,
1.0,3.0,8.0,
1.0,4.0,7.0,
2.0,3.0,7.0,
2.0,4.0,6.0,
1.0,2.0,3.0,6.0,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章