问题描述:
在给定的集合中挑选出所有和为C的子集和。
在(2)的算法框架基础上:
import java. util.Vector ;
public class Subset extends CombineProblem {
int[] arr ;
int c;
public Subset(int[] arr , int c, int n) {
this.flag = false ;
this.n = n;
this.x = new Integer[n];
this.arr = arr;
this.c = c;
}
@Override
public Vector<Comparable> makeIterm (int k) {
Vector vec = new Vector();
for ( int i = 0 ; i <= 1 ; i++) {
vec .add( i);
}
return vec;
}
@Override
public boolean complete(int k) {
int sum = 0 ;
if ( k >= n)
for ( int i = 0 ; i < n; i++) {
sum += ( arr[i ] * (Integer) x [i]);
}
return sum == c;
}
@Override
public void printsolution(int k) {
for ( int i = 0 ; i < n; i++) {
if (( Integer) x [i] == 1) {
System .out. print(arr [i] + " ");
}
}
System .out. println("" );
}
@Override
public boolean isPartial(int k) {
int sum = 0 ;
for ( int i = 0 ; i < k; i++)
sum += ( arr[i ] * (Integer) x [i]);
return sum <= c;
}
}
主函数:
public class Main {
public static void main(String [] args) {
int[] arr = { 1 , 2 , 3 , 4 , 5 , 6 , - 1, -3, -5 };
Problem p = new Subset(arr , 6 , arr. length);
p .explore(0);
if (! p.flag) {
System .out. println("no solution!" );
}
}
}
输出结果: