- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 76 lines of Python from the credited upstream file maximum-length-of-a-concatenated-string-with-unique-characters.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4power = [1]5log2 = {1:0}6for i in xrange(1, 26):7 power.append(power[-1]<<1)8 log2[power[i]] = i9 10 11class Solution(object):12 def maxLength(self, arr):13 """14 :type arr: List[str]15 :rtype: int16 """17 def bitset(s):18 result = 019 for c in s:20 if result & power[ord(c)-ord('a')]:21 return 022 result |= power[ord(c)-ord('a')]23 return result24 25 def number_of_one(n):26 result = 027 while n:28 n &= n-129 result += 130 return result31 32 dp = [0]33 for x in arr:34 x_set = bitset(x)35 if not x_set:36 continue37 curr_len = len(dp)38 for i in xrange(curr_len):39 if dp[i] & x_set:40 continue41 dp.append(dp[i] | x_set)42 return max(number_of_one(s_set) for s_set in dp)43 44 454647class Solution2(object):48 def maxLength(self, arr):49 """50 :type arr: List[str]51 :rtype: int52 """ 53 def bitset(s):54 result = 055 for c in s:56 if result & power[ord(c)-ord('a')]:57 return 058 result |= power[ord(c)-ord('a')]59 return result60 61 bitsets = [bitset(x) for x in arr]62 result = 063 for i in xrange(power[len(arr)]):64 curr_bitset, curr_len = 0, 065 while i:66 j = i & -i 67 i ^= j68 j = log2[j] 69 if not bitsets[j] or (curr_bitset & bitsets[j]):70 break71 curr_bitset |= bitsets[j]72 curr_len += len(arr[j])73 else:74 result = max(result, curr_len)75 return result76