题目描述
class Solution {
public :
int backPackX ( int n) {
}
} ;
题目解析
完全背包
思路和lintcode:440 背包问题 III 一样
定义: dp[i][j]表示用i件物品,j元情况下最多能有多少价值 dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - prices[i]] + prices[i]) 当前物品不取VS取
class Solution {
public :
int backPackX ( int n) {
std:: vector< int > prices = { 150 , 250 , 350 } ;
std:: vector< std:: vector< int >> dp ( 4 , std:: vector < int > ( n + 1 ) ) ;
for ( int i = 1 ; i <= 3 ; ++ i) {
int price = prices[ i - 1 ] ;
for ( int j = 1 ; j <= n; ++ j) {
if ( j >= price) {
dp[ i] [ j] = std:: max (
dp[ i - 1 ] [ j] ,
dp[ i - 1 ] [ j - price] + price
) ;
} else {
dp[ i] [ j] = dp[ i - 1 ] [ j] ;
}
}
}
return n - dp[ 3 ] [ n] ;
}
} ;
定义 dp[j]:手上有 j 元,最多能花出去多少;
class Solution {
public :
int backPackX ( int n) {
std:: vector< int > prices = { 150 , 250 , 350 } ;
std:: vector< int > dp ( n + 1 ) ;
dp[ 0 ] = 0 ;
int len = prices. size ( ) ;
for ( int i = 1 ; i <= len; ++ i) {
int price = prices[ i - 1 ] ;
for ( int j = price; j <= n; ++ j) {
dp[ j] = std:: max ( dp[ j] , dp[ j - price] + price ) ;
}
}
return n - dp[ n] ;
}
} ;
定义 dp[j]:手上有 j 元,买东西后最少剩余多少(剩余的钱给小费);
思路:尽量将钱都用来买东西 => 背包尽量装满 状态:dp[i]表示是否能花费j元 转移方程:dp[i] = dp[i - 150] || dp[i - 250] || dp[i - 350] 初始条件:dp[0] = true 答案:n - i for the first dp[i] is true, i = n ... 150
class Solution {
public :
int backPackX ( int n) {
if ( n < 150 ) return n;
if ( n < 250 ) return n- 150 ;
if ( n < 300 ) return n- 250 ;
if ( n < 350 ) return n- 300 ;
return n% 50 ;
}
} ;