1096. Brace Expansion II

Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.

Grammar can best be understood through simple examples:

  • Single letters represent a singleton set containing that word.
    • R("a") = {"a"}
    • R("w") = {"w"}
  • When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.
    • R("{a,b,c}") = {"a","b","c"}
    • R("{ {a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)
  • When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
    • R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
    • R("{a{b,c}}{ {d,e},f{g,h}}") = R("{ab,ac}{dfg,dfh,efg,efh}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}

Formally, the 3 rules for our grammar:

  • For every lowercase letter x, we have R(x) = {x}
  • For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
  • For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.

Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.

 

Example 1:

Input: "{a,b}{c{d,e}}"
Output: ["acd","ace","bcd","bce"]

Example 2:

Input: "{
    {a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.

 

Constraints:

  1. 1 <= expression.length <= 50
  2. expression[i] consists of '{''}'','or lowercase English letters.
  3. The given expression represents a set of words based on the grammar given in the description.

思路:递归,

1. 第2个op就是set的union

2. 第3个op就是笛卡尔乘积

from itertools import product
class Solution(object):
    def braceExpansionII(self, expression):
        """
        :type expression: str
        :rtype: List[str]
        """
        if len(expression)==0: return ''
        st=[[]]
        cnt=start=0
        for i,v in enumerate(expression):
            if v=='{':
                if cnt==0: start=i+1
                cnt+=1
            elif v=='}':
                # 另外一个笛卡尔乘积的元素
                cnt-=1
                if cnt==0: st[-1].append(self.braceExpansionII(expression[start:i]))
            elif v==',':
                # 开辟另外一个数组存放另外一个新的笛卡尔乘积
                if cnt==0: st.append([])
            else:
                # 独立的字母,也看作笛卡尔乘积的一个元素,因为只有一个字母,所以笛卡尔乘积正好只选整个!
                if cnt==0: st[-1].append([v])
        
        res=set()
        for s in st:
            tmp=product(*s) # 计算一个笛卡尔乘积
            tmp=map(''.join, tmp) 
            res=res|set(tmp) # 不同笛卡尔乘积结果取union
        return sorted(res)
        
s=Solution()
print(s.braceExpansionII("{a,b}c{d,e}f"))
#print(s.braceExpansionII('{a,b}{c{d,e}}'))
#print(s.braceExpansionII('{
    {a,z},a{b,c},{ab,z}}'))

一开始想一层层的剥离括号,但是一直WA,需要考虑的case很多,如下,洋洋洒洒写了一大坨,但是还是fail了,还是抓住op计算的本质会好点

from collections import Counter
class Solution(object):
    def braceExpansionII(self, expression):
        """
        :type expression: str
        :rtype: List[str]
        """
        def merge(s1,s2):
            s=set()
            for ss1 in s1:
                for ss2 in s2:
                    s.add(ss1+ss2)
            return s
        
        def helper(s):
            if len(s)==0: return set()
            if '{' not in s: return set(s.split(','))
            
            cnt=0
            parts=[]
            ops=[]
            start=0
            for i in range(len(s)):
                if s[i]=='{': 
                    if cnt==0:
                        if s[start:i]!='':
                            if s[i-1]==',':
                                parts.append(s[start:i-1])
                                ops.append('add')
                            else:
                                parts.append(s[start:i])
                                ops.append('merge')
                            start=i
                    cnt+=1
                elif s[i]=='}':
                    cnt-=1
                    if cnt==0:
                        parts.append(s[start:i+1])
                        if i+1

ps:这种题目写起来就是很tricky....

你可能感兴趣的:(leetcode,递归)