body
{
font-family: 微软雅黑,"Microsoft YaHei", Georgia,Helvetica,Arial,sans-serif,宋体, PMingLiU,serif;
font-size: 10.5pt;
line-height: 1.5;
}
html, body
{
}
h1 {
font-size:1.5em;
font-weight:bold;
}
h2 {
font-size:1.4em;
font-weight:bold;
}
h3 {
font-size:1.3em;
font-weight:bold;
}
h4 {
font-size:1.2em;
font-weight:bold;
}
h5 {
font-size:1.1em;
font-weight:bold;
}
h6 {
font-size:1.0em;
font-weight:bold;
}
img {
border:0;
max-width: 100%;
height: auto !important;
}
blockquote {
margin-top:0px;
margin-bottom:0px;
}
table {
border-collapse:collapse;
border:1px solid #bbbbbb;
}
td {
border-collapse:collapse;
border:1px solid #bbbbbb;
}
问题描述:
在给定的集合中挑选出所有和为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!" );
}
}
}
输出结果:
6
2 4
1 5
1 2 3