1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| struct pairhash { public: template <class T, class U> std::size_t operator () (const std::pair<T, U>& p) const { std::hash<T> Thasher; std::hash<U> Uhasher; return Thasher(p.first) ^ Uhasher(p.second); } };
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int n = cardPoints.size(); unordered_map<pair<int, int>, int, pairhash> scores; subMaxScore(cardPoints, 0, n, scores, k);
return scores[make_pair(0, n)]; }
private: int subMaxScore(vector<int>& cardPoints, int beg, int end, unordered_map<pair<int, int>, int, pairhash>& scores, int k) { if (k == 0) return 0; pair<int, int> cur = make_pair(beg, end); if (scores.count(cur)) return scores[cur];
int leftScore = cardPoints[beg], rightScore = cardPoints[end - 1]; pair<int, int> left = make_pair(beg + 1, end), right = make_pair(beg, end - 1); if (scores.count(left)) leftScore += scores[left]; else leftScore += subMaxScore(cardPoints, beg + 1, end, scores, k - 1); if (scores.count(right)) rightScore += scores[right]; else rightScore += subMaxScore(cardPoints, beg, end - 1, scores, k - 1); scores[cur] = max(leftScore, rightScore); return scores[cur]; } };
|