LeetCode 1255 - Maximum Score Words Formed by Letters


https://leetcode.com/problems/maximum-score-words-formed-by-letters/
Given a list of words, list of  single letters (might be repeating) and score of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a''b''c', ... ,'z' is given by score[0]score[1], ... , score[25] respectively.

Example 1:
Input: 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]
Output: 23
Explanation:
Score  a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
Words "dad" and "dog" only get a score of 21.
Example 2:
Input: 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]
Output: 27
Explanation:
Score  a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
Word "xxxz" only get a score of 25.
Example 3:
Input: 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]
Output: 0
Explanation:
Letter "e" can only be used once.

Constraints:
  • 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] contains only lower case English letters
X. https://www.acwing.com/solution/LeetCode/content/6125/
(二进制枚举) O(n2^n)
  1. 枚举二进制的集合,从 1 到 2n1
  2. 每一位 0 或 1 代表选或不选。

时间复杂度

  • 需要 O(2n) 种情况全部枚举,每次枚举后需要 O(n) 的时间找到被选出的单词,故时间复杂度为 O(n2^n)

空间复杂度

  • 仅需要常数的额外空间。
    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score) {
        int n = words.size();
        int ans = 0;

        vector<int> valid(26, 0);
        for (char c : letters)
            valid[c - 'a']++;

        for (int S = 1; S < (1 << n); S++) {
            vector<int> used(26, 0);
            int tot = 0;
            for (int i = 0; i < n; i++)
                if ((S >> i) & 1) {
                    for (char c : words[i]) {
                        used[c - 'a']++;
                        tot += score[c - 'a'];
                    }
                }

            bool flag = true;
            for (int i = 0; i < 26; i++)
                if (used[i] > valid[i]) {
                    flag = false;
                    break;
                }

            if (flag)
                ans = max(ans, tot);
        }

        return ans;
    }


X.
https://www.icode9.com/content-4-554788.html
用回溯法遍历各种可能性,时间复杂度 O(2^n),可以使用一些剪枝的技巧。
private static int result;
    private static Map<String, Integer> scoreMap = null;
    private static int[] lettersNumber;

    public int maxScoreWords(String[] words, char[] letters, int[] score) {
        result = 0;
        scoreMap = new HashMap<>();
        lettersNumber = new int[26];
        char[] chars;
        int wordScore;
        for (String word : words) {
            chars = word.toCharArray();
            wordScore = 0;
            for (char aChar : chars) {
                wordScore += score[aChar - 'a'];
            }
            scoreMap.put(word, wordScore);
        }
        for (char letter : letters) {
            lettersNumber[letter - 'a']++;
        }
        Arrays.sort(words, (a, b) -> scoreMap.get(b) - scoreMap.get(a));
        dfsHelper(0, 0, words);
        return result;
    }

    private void dfsHelper(int score, int index, String[] words) {
        if (index >= words.length) {
            result = Math.max(result, score);
            return;
        }
        String word = words[index];
        if ((score + scoreMap.get(word) * (words.length - index)) <= result) {
            return;
        }
        char[] chars = word.toCharArray();
        int len = 0;
        for (char aChar : chars) {
            if (lettersNumber[aChar - 'a'] > 0) {
                lettersNumber[aChar - 'a']--;
                len++;
            } else {
                break;
            }
        }
        if (len == chars.length) {
            score += scoreMap.get(word);
            dfsHelper(score, index + 1, words);
            score -= scoreMap.get(word);
        }
        for (int i = 0; i < len; i++) {
            lettersNumber[chars[i] - 'a']++;
        }
        dfsHelper(score, index + 1, words);
    }

https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/425129/java-backtrack-similar-to-78.-Subsets-1ms-beats-100


Similar to 78. Subsets, use backtrack to solve the problem.
    public int maxScoreWords(String[] words, char[] letters, int[] score) {
        if (words == null || words.length == 0 || letters == null || letters.length == 0 || score == null || score.length == 0) return 0;
        int[] count = new int[score.length];
        for (char ch : letters) {
            count[ch - 'a']++;
        }
        int res = backtrack(words, count, score, 0);
        return res;
    }
    int backtrack(String[] words, int[] count, int[] score, int index) {
        int max = 0;
        for (int i = index; i < words.length; i++) {
            int res = 0;
            boolean isValid = true;
            for (char ch : words[i].toCharArray()) {
                count[ch - 'a']--;
                res += score[ch - 'a'];
                if (count[ch - 'a'] < 0) isValid = false;
            }
            if (isValid) {
                res += backtrack(words, count, score, i + 1);
                max = Math.max(res, max);
            }
            for (char ch : words[i].toCharArray()) {
                count[ch - 'a']++;
                res = 0;
            }
        }
        return max;
    }
https://leetcode.jp/leetcode-1255-maximum-score-words-formed-by-letters-%E8%A7%A3%E9%A2%98%E6%80%9D%E8%B7%AF%E5%88%86%E6%9E%90/
先看words数组中的单词能不能被拼写出来,这取决于letters数组中有没有相应足够多的字符,如果没有肯定是要被pass掉的,关键在于,如果letters数组中存在足够多的字符能够拼出当前单词,那么我们就要做出选择,是拼当前字符还是不拼,这两种选择哪种会导致全局结果更好,当前是无法得知的,因此要递归到子问题中继续求解。
解题步骤大概如下:
  1. 先统计下letters数组中26个小写字母各有多少个。
  2. 从words数组中第一个index的字符串开始递归,如果letters数组中没有足够多的字符能够组成当前字符串,index加一递归到下一层。
  3. 反之,我们有两种选择,第一,将当前字符拼写出来,同时在letters数组中减去使用掉的字符数量,再算出当前字符串能够得到的积分,最后index加一递归到下一层。第二中选择是,我们不拼写当前字符串,直接index加一递归到下一层。比较两种选择结果更好的一方返回。
  4. 递归结束条件为index到达words数组末尾。
public int maxScoreWords(String[] words, char[] letters, int[] score) {
    int[] letterCount = new int[26]; // 用来统计每个字符的个数
    // 统计每个字符的个数
    for(char c : letters) letterCount[c-'a']++;
    // 从第一个字符串开始递归
    return helper(words, letterCount, score, 0, 0);
}
// words:words数组
// letterCount:letters数组中每种字符的个数
// score:score数组
// sum:当前为止的累计得分
// index:当前index
int helper(String[] words, int[] letterCount, int[] score, int sum, int index){
    // 如果index达到数组末尾,递归结束,返回当前累计得分
    if(index == words.length) return sum;
    String word=words[index]; // 当前字符串
    int res = 0; // 返回结果(累计得分)
    // 如果存在足够的字符能够组成当前字符串
    if(hasWord(word, letterCount)){
        // 第一种选择:拼写出当前字符串
        int s=0; // 当前字符串能够拿到的分数
        // 循环字符串中每个字符
        for(int i=0;i<word.length();i++){
            // 消耗一个当前字符
            letterCount[word.charAt(i)-'a']--;
            // 累加分数
            s+=score[word.charAt(i)-'a'];
        }
        // sum加上当前字符串分数,index加一,递归到下一层
        res = helper(words, letterCount, score, sum+s, index+1);
        // 递归后将letterCount数组个数还原
        for(int i=0;i<word.length();i++){
            letterCount[word.charAt(i)-'a']++;
        }
    }
    // 第二种选择:不拼写出当前字符串,即直接index加一递归到下一层
    // 返回两种选择的最大值
    return Math.max(res, helper(words, letterCount, score, sum, index+1));
}
// 查看letterCount中是否含有足够的字符以能够组成字符串word
boolean hasWord(String word, int[] letterCount){
    int[] count = new int[26];
    for(int i=0;i<word.length();i++){
        count[word.charAt(i)-'a']++;
    }
    for(int i=0;i<26;i++){
        if(count[i]>letterCount[i]){
            return false;
        }
    }
    return true;
}
https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/425104/Detailed-Explanation-using-Recursion
  • Since the number of words is quite less (14), we can just generate all the subsets. Let's call a subset valid if all the words in that subset can be formed by using the given letters. It is clear that we need to maximize the score of valid subsets. To do this, we generate all subsets, and check if it is valid. If it is, we find its score and update the global maxima.
  • To generate the subsets, we create a function call generate_subset(words, n) which generate all the subsets of the vector words. To quickly recap, we have 2 choices for the last element, either to take it or to leave it. We store this choice in an array called taken where taken[i] represent that the i-th element was taken in our journey. We then recurse for the remaining elements.
  • When n becomes zero, it means we cannot make any more choices. So now, we traverse our taken array to find out the elements in this subset. Then we count the frequency of each letter in this subset. If the frequency of each letter is under the provided limit, it means it is a valid subet. Hence, we find the score of this subset and update the maxima
public:
    vector<bool> taken;
    vector<int> count;
    vector<int> score;
    int max_sum = 0;
    
    void update_score(vector<string>& words);
    void generate_subset(vector<string>& words, int n);
    int maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score);
};

void Solution :: generate_subset(vector<string>& words, int n)
{
    if(n == 0)
    {
        update_score(words);
        return;
    }
    
    taken[n-1] = true;
    generate_subset(words, n-1);
    
    taken[n-1] = false;
    generate_subset(words, n-1);
}

void Solution :: update_score(vector<string>& words)
{
    int current_score = 0;
    vector<int> freq(26, 0);
    
    for(int i = 0; i < words.size(); i++)
    {
        if(taken[i])
        {
            for(auto ele : words[i])
            {
                int ind = ele - 'a';
                current_score += score[ind];
                freq[ind]++;
                
                if(freq[ind] > count[ind])
                      return;
            }
        }
    }
                      
    max_sum = max(max_sum, current_score);
}
                      
int Solution :: maxScoreWords(vector<string>& words, vector<char>& letters, vector<int>& score)
{
    taken.resize(words.size(), false);
    count.resize(26, 0);
    this->score = score;
    
    for(auto ele : letters)
        count[ele - 'a']++;
    
    int n = words.size();
    generate_subset(words, n);
    
    return max_sum;
}


Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts