题目
解法:回溯法
public class Bag {
public int [ ] weight;
public int [ ] value;
public int [ ] take;
int curWeight = 0 ;
int curValue = 0 ;
int bestValue = 0 ;
int [ ] bestChoice;
int count;
int maxWeight = 0 ;
public void init ( int [ ] weight, int [ ] value, int maxWeight) {
if ( weight == null || weight. length == 0
|| value == null || value. length == 0
|| weight. length != value. length || maxWeight <= 0 ) {
System. out. println ( "args wrong!" ) ;
return ;
}
this . value = value;
this . weight = weight;
this . maxWeight = maxWeight;
count = value. length;
take = new int [ count] ;
bestChoice = new int [ count] ;
}
public int [ ] maxValue ( int x) {
if ( x > count - 1 ) {
if ( curValue > bestValue) {
bestValue = curValue;
for ( int i = 0 ; i < take. length; i++ ) {
bestChoice[ i] = take[ i] ;
}
}
} else {
for ( int i = 0 ; i < 2 ; i++ ) {
take[ x] = i;
if ( i == 0 ) {
maxValue ( x + 1 ) ;
} else {
if ( curWeight + weight[ x] <= maxWeight) {
curWeight += weight[ x] ;
curValue += value[ x] ;
maxValue ( x + 1 ) ;
curWeight -= weight[ x] ;
curValue -= value[ x] ;
}
}
}
}
return bestChoice;
}
public static void main ( String[ ] args) {
Bag question = new Bag ( ) ;
question. init ( new int [ ] { 7 , 3 , 4 , 5 } , new int [ ] { 42 , 12 , 40 , 25 } , 10 ) ;
int [ ] result = question. maxValue ( 0 ) ;
}
}