你将会得到一份单词表 words,一个字母表 letters (可能会有重复字母),以及每个字母对应的得分情况表 score。 请你帮忙计算玩家在单词拼写游戏中所能获得的「最高得分」:能够由 letters 里的字母拼写出的 任意 属于 words 单词子集中,分数最高的单词集合的得分。 单词拼写游戏的规则概述如下: 来源:力扣(LeetCode) 32 ms 8.7 MB
1. 题目
示例 1: 输入:words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0] 输出:23 解释: 字母得分为 a=1, c=9, d=5, g=3, o=2 使用给定的字母表 letters,我们可以拼写单词 "dad" (5+1+5)和 "good" (3+2+2+5), 得分为 23 。 而单词 "dad" 和 "dog" 只能得到 21 分。 示例 2: 输入:words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10] 输出:27 解释: 字母得分为 a=4, b=4, c=4, x=5, z=10 使用给定的字母表 letters,我们可以组成单词 "ax" (4+5), "bx" (4+5) 和 "cx" (4+5) , 总得分为 27 。 单词 "xxxz" 的得分仅为 25 。 示例 3: 输入:words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0] 输出:0 解释: 字母 "e" 在字母表 letters 中只出现了一次,所以无法组成单词表 words 中的单词。 提示: 1 <= words.length <= 14 1 <= words[i].length <= 15 1 <= letters.length <= 100 letters[i].length == 1 score.length == 26 0 <= score[i] <= 10 words[i] 和 letters[i] 只包含小写的英文字母。
链接:https://leetcode-cn.com/problems/maximum-score-words-formed-by-letters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。2. 解题
class Solution { int maxscore = 0; public: int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) { int n = words.size(), i; vector<int> count(26,0); for(i = 0; i < letters.size(); ++i) count[letters[i]-'a']++;//可使用的字母数量 dfs(words, count, score, 0, 0); return maxscore; } void dfs(vector<string>& words, vector<int>& count, vector<int>& score, int i, int sc) { if(i == words.size()) { if(canAdd(count))//所选单词组合满足条件 maxscore = max(maxscore, sc); return; } //加入该单词 for(int j = 0; j < words[i].size(); ++j) { //更新单词得分,计数减少 sc += score[words[i][j]-'a']; count[words[i][j]-'a']--; } dfs(words, count, score, i+1, sc); for(int j = 0; j < words[i].size(); ++j) { //回溯,计数重置,得分减去 sc -= score[words[i][j]-'a']; count[words[i][j]-'a']++; } //不加入该单词 dfs(words, count, score, i+1, sc); } bool canAdd(vector<int>& count) { for(int i = 0; i < 26; ++i) { if(count[i] < 0) return false; } return true; } };
本网页所有视频内容由 imoviebox边看边下-网页视频下载, iurlBox网页地址收藏管理器 下载并得到。
ImovieBox网页视频下载器 下载地址: ImovieBox网页视频下载器-最新版本下载
本文章由: imapbox邮箱云存储,邮箱网盘,ImageBox 图片批量下载器,网页图片批量下载专家,网页图片批量下载器,获取到文章图片,imoviebox网页视频批量下载器,下载视频内容,为您提供.
阅读和此文章类似的: 全球云计算