题目链接:
题解
dynamic programing
需要用到进制转换来表示状态,或者可以直接用一个vector来保存状态。
代码
1、未优化,超时代码:
class Solution {
public:
int max(int x,int y){ return x>y?x:y; }
int min(int x,int y){ return x>y?y:x; }
int dfs(vector<int>& price,vector<vector<int> >& special, map<vector<int>,int>& dp,vector<int> cur){
if(dp.count(cur)) return dp[cur];
int &res=dp[cur]=INF;
for(int i=0;i<special.size();i++){
bool flag=true;
vector<int> nex;
for(int j=0;j<price.size();j++){
int tmp=cur[j]-special[i][j];
if(tmp<0){
flag=false; break;
}
nex.push_back(tmp);
}
if(flag){
res=min(res,dfs(price,special,dp,nex)+special[i][special[i].size()-1]);
}
}
//这里可以优化,能优化的原因是因为转移顺序是可调整的
for(int i=0;i<price.size();i++){
vector<int> nex(cur);
if(nex[i]>0){
nex[i]--;
res=min(res,dfs(price,special,dp,nex)+price[i]);
}
}
return res;
}
int shoppingOffers(vector<int>& price, vector<vector<int> >& special, vector<int>& needs) {
map<vector<int>,int> dp;
vector<int> start;
for(int i=0;i<price.size();i++){
start.push_back(0);
}
dp[start]=0;
vector<int> cur(needs);
return dfs(price,special,dp,cur);
}
private:
const static int INF=0x3f3f3f3f;
};
2、优化之后的代码
class Solution {
public:
int max(int x,int y){ return x>y?x:y; }
int min(int x,int y){ return x>y?y:x; }
int dfs(vector<int>& price,vector<vector<int> >& special, map<vector<int>,int>& dp,vector<int> cur){
if(dp.count(cur)) return dp[cur];
int res=INF;
for(int i=0;i<special.size();i++){
bool flag=true;
vector<int> nex;
for(int j=0;j<price.size();j++){
int tmp=cur[j]-special[i][j];
if(tmp<0){
flag=false; break;
}
nex.push_back(tmp);
}
if(flag){
res=min(res,dfs(price,special,dp,nex)+special[i][special[i].size()-1]);
}
}
//这里进行了优化
int noSpecial=0;
for(int i=0;i<cur.size();i++){
noSpecial+=cur[i]*price[i];
}
res=min(res,noSpecial);
return dp[cur]=res;
}
int shoppingOffers(vector<int>& price, vector<vector<int> >& special, vector<int>& needs) {
map<vector<int>,int> dp;
vector<int> start;
for(int i=0;i<price.size();i++){
start.push_back(0);
}
dp[start]=0;
vector<int> cur(needs);
return dfs(price,special,dp,cur);
}
private:
const static int INF=0x3f3f3f3f;
};