一、最后一块石头的重量2
class Solution {
public int lastStoneWeightII ( int [ ] stones) {
int sum = 0 ;
for ( int stone : stones) {
sum += stone;
}
int target = sum / 2 ;
int [ ] dp = new int [ target + 1 ] ;
for ( int stone : stones) {
for ( int i = target; i >= stone; i-- ) {
dp[ i] = Math . max ( dp[ i] , dp[ i - stone] + stone) ;
}
}
return sum - 2 * dp[ target] ;
}
}
二、目标和
class Solution {
int result = 0 ;
public int findTargetSumWays ( int [ ] nums, int target) {
if ( nums. length == 0 ) return 0 ;
backtrack ( nums, 0 , target) ;
return result;
}
void backtrack ( int [ ] nums, int i, int remain) {
if ( i == nums. length) {
if ( remain == 0 ) {
result++ ;
}
return ;
}
remain += nums[ i] ;
backtrack ( nums, i + 1 , remain) ;
remain -= nums[ i] ;
remain -= nums[ i] ;
backtrack ( nums, i + 1 , remain) ;
remain += nums[ i] ;
}
}
三、一和零
public class Solution {
public int findMaxForm ( String [ ] strs, int m, int n) {
int len = strs. length;
int [ ] [ ] [ ] dp = new int [ len + 1 ] [ m + 1 ] [ n + 1 ] ;
for ( int i = 1 ; i <= len; i++ ) {
int [ ] count = countZeroAndOne ( strs[ i - 1 ] ) ;
for ( int j = 0 ; j <= m; j++ ) {
for ( int k = 0 ; k <= n; k++ ) {
dp[ i] [ j] [ k] = dp[ i - 1 ] [ j] [ k] ;
int zeros = count[ 0 ] ;
int ones = count[ 1 ] ;
if ( j >= zeros && k >= ones) {
dp[ i] [ j] [ k] = Math . max ( dp[ i - 1 ] [ j] [ k] , dp[ i - 1 ] [ j - zeros] [ k - ones] + 1 ) ;
}
}
}
}
return dp[ len] [ m] [ n] ;
}
private int [ ] countZeroAndOne ( String str) {
int [ ] cnt = new int [ 2 ] ;
for ( char c : str. toCharArray ( ) ) {
cnt[ c - '0' ] ++ ;
}
return cnt;
}
}