2019-06-22 文稿

题目:华为应用商城举办下应用得积分的活动,月末你还有40兆流量未使用,现在有4个应用可以下载,每个应用需要的流量分别为 12, 13, 23, 36,下载每个应用获得的积分为 10, 11, 20, 30,求用户可以获得的最大积分数为多少?

对应到背包问题,V=40,C={12, 13, 23, 36}, W= {10, 11, 20, 30}。

def solution1(V, C, W):
    # 如果没有货物,返回0
    if len(C)==0: return 0
    # 不选第一个物品时的结果
    ret0 = solution1(V, C[1:], W[1:])
    # 如果第一个物品的占用空间大于容量V,则必不选
    if C[0]>V: return ret0
    # 选第一个物品时的结果
    ret1 = W[0] + solution1(V-C[0], C[1:], W[1:])
    # 返回选与不选之间的最大值
    return max(ret0, ret1)

V = 40
C = [12, 13, 23, 36]
W = [10, 11, 20, 30]
print(solution1(V, C, W))

对应的c++代码为:

#include <iostream>
#include <vector>

using namespace std;

int solution1(int V, vector<int> C, vector<int> W){
    if(C.size()==0) return 0;
    int ret0 = solution1(V, vector<int>(C.begin()+1, C.end()),
            vector<int>(W.begin()+1, W.end()));
    if(C[0]>V) return ret0;
    int ret1 = W[0]+solution1(V-C[0], vector<int>(C.begin()+1, C.end()),
            vector<int>(W.begin()+1, W.end()));
    return ret0>ret1?ret0:ret1;
}

int main(){
    int V = 40;
    vector<int> C{12, 13, 23, 36};
    vector<int> W{10, 11, 20, 30};
    cout << solution1(V, C, W) << endl;
    return 0;
}

缺点:

  • 存在大量重复计算;
  • 需要大量的数组拷贝;

解决方法:解决第一个问题,通过字典记录下所有求解过的问题。

def solution2(V, C, W, record):
    if len(C)==0: return 0
    if (V, len(C)) in record: return record[(V, len(C))] # +++
    ret0 = solution2(V, C[1:], W[1:], record);
    if C[0]>V: return ret0
    ret1 = W[0] + solution2(V-C[0], C[1:], W[1:], record)
    record[(V, len(C))] = max(ret0, ret1) # +++
    return max(ret0, ret1)

V = 40
C = [12, 13, 23, 36]
W = [10, 11, 20, 30]
print(solution2(V, C, W, dict()))

对应的C++代码:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int solution2(int V, vector<int> C, vector<int> W, map<pair<int,int>,int>& record){
    pair<int, int> situation(V, C.size());  //+++
    auto p = record.find(situation);        //+++
    if(p!=record.end()) return p->second;   //+++
    if(C.size()==0) return 0;
    int ret0 = solution2(V, vector<int>(C.begin()+1, C.end()),
            vector<int>(W.begin()+1, W.end()),record);
    if(C[0]>V) return ret0;
    int ret1 = W[0]+solution2(V-C[0], vector<int>(C.begin()+1, C.end()),
            vector<int>(W.begin()+1, W.end()), record);
    record[situation] = ret0>ret1?ret0:ret1;//+++
    return ret0>ret1?ret0:ret1;
}

int main(){
    int V = 40;
    vector<int> C{12, 13, 23, 36};
    vector<int> W{10, 11, 20, 30};
    map<pair<int,int>, int> record; //+++
    cout << solution2(V, C, W, record) << endl;
    return 0;
}

解决第二个问题:递归调用时需要大量的数组拷贝,解决数组拷贝问题 -- 增加一个参数证明带选择的物品。

def solution3(V, C, W, record, i):
    if i>=len(C): return 0
    if (V, i) in record: return record[(V, i)]
    ret0 = solution3(V, C, W, record, i+1);
    if C[i]>V: return ret0
    ret1 = W[i] + solution3(V-C[i], C, W, record, i+1)
    record[(V, i)] = max(ret0, ret1) 
    return max(ret0, ret1)

V = 40
C = [12, 13, 23, 36]
W = [10, 11, 20, 30]
print(solution3(V, C, W, dict(), 0))

对应的c++代码:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int solution3(int V, vector<int>& C, vector<int>& W, map<pair<int,int>,int>& record, int i){
    pair<int, int> situation(V, C.size());
    auto p = record.find(situation);
    if(p!=record.end()) return p->second;
    if(i>=C.size()) return 0;
    int ret0 = solution3(V, C, W, record, i+1);
    if(C[i]>V) return ret0;
    int ret1 = W[i]+solution3(V-C[i], C, W, record, i+1);
    record[situation] = ret0>ret1?ret0:ret1;
    return ret0>ret1?ret0:ret1;
}
int main(){
    int V = 40;
    vector<int> C{12, 13, 23, 36};
    vector<int> W{10, 11, 20, 30};
    map<pair<int,int>, int> record;
    cout << solution3(V, C, W, record, 0) << endl;
    return 0;
}

注意:python数组传递时默认是传引用,c++中vector传递时默认是值传递。

另一种思路:用一个 (N+1) × (V+1) 的数组A记录计算过的结果,索引(i, v) 表示如果物品为前i个,容量为v时,可以获取的最大价值。转移函数 F(v, i)=max(F(v, i-1), W_i+F(v-C_i, i-1)) 可以写成:A[i][v]=max(A[i-1][v], W_i+A[i-1][v-C_i])
注意:如果v-C_i<0, 则 A[i-1][v-C_i]=0。代码为:

def solution4(V, C, W):
    N = len(C)
    record = [[0]*(V+1) for i in range(N+1)]
    for i in range(1, N+1):
        for v in range(1, V+1):
            ret1 = record[i-1][v]
            ret2 = 0
            if v-C[i-1] >= 0:
                ret2 = W[i-1]+record[i-1][v-C[i-1]]
            record[i][v] = max(ret1, ret2)
    return record[N][V]
V = 40
C = [12, 13, 23, 36]
W = [10, 11, 20, 30]
print(solution4(V, C, W))

对应c++代码:

#include <iostream>
#include <vector>
using namespace std;

int solution4(int V,const vector<int>& C,const vector<int>& W){
    vector< vector<int> > record;
    int N = C.size();
    for(int i=0; i<N+1; ++i)
        record.push_back(vector<int>(V+1, 0));
    for(int i=1; i<N+1; ++i){
        for(int v=1; v<V+1; ++v){
            int ret1 = record[i-1][v];
            int ret2 = 0;
            if(v-C[i-1]>=0)
                ret2 = W[i-1]+record[i-1][v-C[i-1]];
            record[i][v] = ret1>ret2?ret1:ret2;
        }
    }
    return record[N][V];
}
int main(){
    int V = 40;
    vector<int> C{12, 13, 23, 36};
    vector<int> W{10, 11, 20, 30};
    cout << solution4(V, C, W) << endl;
    return 0;
}

上述算法的时间复杂度为:O(NV),空间复杂度为O(NV),下面将空间复杂度降为 O(V)。(如果要指明选出那几件物品,则时间复杂度不能降低)。

def solution5(V, C, W):
    N = len(C)
    record = [0]*(V+1)
    for i in range(0, N):
        for v in range(V, -1, -1):
            ret1 = record[v]
            ret2 = 0
            if v-C[i] >= 0:
                ret2 = W[i]+record[v-C[i]]
            record[v] = max(ret1, ret2)
    return record[V]
V = 40
C = [12, 13, 23, 36]
W = [10, 11, 20, 30]
print(solution5(V, C, W))

对应的c++代码为:

#include <iostream>
#include <vector>

using namespace std;

int solution5(int V,const vector<int>& C,const vector<int>& W){
    vector<int> record(V+1, 0);
    int N = C.size();
    for(int i=0; i<N; ++i){
        for(int v=V; v>=0; --v){
            int ret1 = record[v];
            int ret2 = 0;
            if(v-C[i]>=0)
                ret2 = W[i]+record[v-C[i]];
            record[v] = ret1>ret2?ret1:ret2;
        }
    }
    return record[V];
}
int main(){
    int V = 40;
    vector<int> C{12, 13, 23, 36};
    vector<int> W{10, 11, 20, 30};
    cout << solution5(V, C, W) << endl;
    return 0;
}

非表格形式的解决方法适用于V特别大,而物品数量较少的情况,不可用于完全背包问题。

表格形式的解决方案适用于V较小,而物品数量较多的情况,可以用于完全背包问题。

备注:

  • 第二种方法,record如果初始化为-inf,则为更好满足容量的背包问题;
def solutionX(V, C, W):
    N = len(C)
    record = [-float('inf')]*(V+1)
    for i in range(0, N):
        for v in range(V, -1, -1):
            ret1 = record[v]
            ret2 = 0
            if v-C[i] >= 0:
                ret2 = W[i]+record[v-C[i]]
            record[v] = max(ret1, ret2)
    return record[V]
  • 第二种方法,如果内层循环方向变化,则变为0-1背包问题;
def solutionY(V, C, W):
    N = len(C)
    record = [0]*(V+1)
    for i in range(0, N):
        for v in range(0, V+1):
            ret1 = record[v]
            ret2 = 0
            if v-C[i] >= 0:
                ret2 = W[i]+record[v-C[i]]
            record[v] = max(ret1, ret2)
    return record[V]

练习转移函数的理解:https://leetcode.com/problems/house-robber/
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). 
Total amount you can rob = 2 + 9 + 1 = 12.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容