算法设计之回溯法
a.子集和问题
public class SubSum1 {
// 解向量
static boolean x[] = new boolean[100];
static int m = 8;
static int count = 0;
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,6};
fun(arr,0,0);
System.out.println(count); // 110
}
public static void printOneSolution(int []arr) {
for(int j=0; j<arr.length; j++) {
if(x[j]) {
System.out.print(arr[j]+" ");
}
}
System.out.println();
}
public static void fun(int []arr,int step,int sum) {
count++;
// 剪枝
if(step>=arr.length || sum>m) {
return;
}
if(sum==m) {
printOneSolution(arr);
}
if(sum<=m) {
x[step] = true;
fun(arr,step+1,sum+arr[step]);
}
x[step] = false;
fun(arr,step+1,sum);
}
}