Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: combination_set = self.generateTilePossibilities(tiles) return len(combination_set) def generateTilePossibilities(self, tiles: str): n = len(tiles) combination_set = set() for index in range(n): combination_set.add(tiles[index]) if n > 1: for index in range(n): tiles_without_n = tiles[0:index] + tiles[index + 1:] additional_combinations = self.generateTilePossibilities( tiles_without_n) combination_set.add(tiles_without_n) for combination in additional_combinations: combination_set.add(combination) for second_index in range(len(combination)): new_tile_combination = combination[ 0:second_index] + tiles[index] + combination[ second_index:] combination_set.add(new_tile_combination) return combination_set
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def count(tiles): #print(tiles) counter = set() if len(tiles) == 1: counter.add(tiles) elif len(tiles) == 2: counter.add(tiles) counter.add(tiles[::-1]) counter.add(tiles[0]) counter.add(tiles[1]) else: for idx, i in enumerate(tiles): x = count(tiles[:idx] + tiles[idx+1:]) extra = set() for j in x: extra.add(tiles[idx] + j) extra.add(j + tiles[idx]) for k in range(1, len(j)-1): extra.add(j[:k] + tiles[idx] + j[k+1:]) x.update(extra) counter.update(x) #print(counter) return counter return len(count(tiles))
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def __init__(self): self.seen = set() self.result = set() def numTilePossibilities(self, tiles: str) -> int: self.dfs(tiles, 0, []) return len(self.result) - 1 def dfs(self, string, idx, path): st = ''.join(path) if st not in self.seen: self.result.update((''.join(p) for p in permutations(st))) self.seen.add(st) for i in range(idx, len(string)): self.dfs(string, i + 1, path + [string[i]])
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: d = {} for i in range(len(tiles)): if (tiles[i] in d): d[tiles[i]] += 1 else: d[tiles[i]] = 1 def countnum(d): if (d == {}): return 0 c = 0 s = set(d.items()) for k, v in s: d[k] -= 1 if (d[k] == 0): del(d[k]) c += 1 + countnum(d) if (k in d): d[k] += 1 else: d[k] = 1 return c return countnum(d)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: res = set() def dfs(path, t): if path not in res: if path: res.add(path) for i in range(len(t)): dfs(path+t[i], t[:i] + t[i+1:]) dfs('', tiles) return len(res)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: res = set() def backtrack(path, curr): if path not in res: if path: res.add(path) for i in range(len(curr)): backtrack(path + curr[i], curr[:i] + curr[i+1:]) backtrack('', tiles) return len(res)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: d=set() for i in range(len(tiles)): for x in list(permutations(tiles,i+1)): d.add(''.join(x)) print(d) return len(d)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: result = set() maxx = len(tiles) def dfs(result,tiles,current_sequence=''): result.add(current_sequence) for t in tiles: tiles_c = tiles.replace(t,'',1) dfs(result,tiles_c,current_sequence+t) dfs(result,tiles) return len(result)-1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: setter = set() res = [] for r in range(1,len(tiles)+1): res.append(list(itertools.permutations(tiles,r))) result = [] for re in res: result.append(list(set(re))) leng = 0 for i in result: leng += len(i) return leng
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: tile_counts = collections.Counter(tiles) len_counts = [1] + [0] * len(tiles) for tile in tile_counts: new_len_counts = [0] * (len(tiles) + 1) num_tiles = tile_counts[tile] for num_inserted in range(num_tiles + 1): for old_len, old_len_count in enumerate(len_counts): new_len = old_len + num_inserted if new_len > len(tiles): break num_patterns = math.comb(new_len, num_inserted) new_len_counts[new_len] += old_len_count * num_patterns len_counts = new_len_counts return sum(len_counts) - 1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: result = set() maxx = len(tiles) def dfs(result,tiles,current_sequence=''): if len(current_sequence) <= maxx and current_sequence!='': result.add(current_sequence) for t in tiles: tiles_c = tiles.replace(t,'',1) dfs(result,tiles_c,current_sequence+t) dfs(result,tiles) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: result = set() maxx = len(tiles) def dfs(result,tiles,current_sequence=''): if current_sequence!='': result.add(current_sequence) for t in tiles: tiles_c = tiles.replace(t,'',1) dfs(result,tiles_c,current_sequence+t) dfs(result,tiles) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: count = {} for i in tiles: if i not in count: count[i] = 0 count[i]+=1 op = set() for ch in count: tempString = ch op.add(tempString) count[ch]-=1 tempCount = count.copy() buildString(tempString,tempCount,op) count[ch]+=1 return len(op) def buildString(currString,count,op): flag = True for i in count: if count[i]!=0: flag = False break if flag: return for ch in count: if count[ch]==0: continue tempString = currString tempString+=ch op.add(tempString) count[ch]-=1 tempCount = count.copy() buildString(tempString,tempCount,op) count[ch]+=1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def dfs(state): res.append(state.copy()) for i in range(len(state)): if state[i]<full_state[i]: state[i] += 1 dfs(state) state[i] -= 1 memo = collections.Counter(tiles) full_state = list(memo.values()) state = [0 for _ in range(len(memo))] res = [] dfs(state) return len(res)-1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: res = {} def dfs(seq, tiles): if seq not in res and seq != '': res[seq] = 1 for i in range(len(tiles)): dfs(seq+tiles[i], tiles[:i]+tiles[i+1:]) dfs('', tiles) return len(res)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def dfs(path, t): if path: result.add(path) for i in range(len(t)): dfs(path + t[i], t[:i]+t[i+1:]) result = set() dfs('', tiles) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def backtracking(idx=0,seq='',remaining=tiles): for i, tile in enumerate(remaining): res.add(seq+tile) backtracking(idx+1, seq+tile, remaining[:i]+remaining[i+1:]) res = set() backtracking() return len(res)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def dfs(elements): if prev_elements: result.add(''.join(prev_elements)) for e in elements: next_elements = elements[:] next_elements.remove(e) prev_elements.append(e) dfs(next_elements) prev_elements.pop() result = set() prev_elements = [] dfs(list(tiles)) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: seqs = set() visits = [False] * len(tiles) def dfs(seq: str, depth: int): if seq: seqs.add(seq) if depth == len(tiles) - 1: return for i in range(len(tiles)): if not visits[i]: visits[i] = True dfs(seq + tiles[i], depth + 1) visits[i] = False dfs('', -1) return len(seqs)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def get_permute(self, opts, cur_sol): for i in range(len(opts)): c = opts[i] cur_sol.append(c) self.solutions.add(''.join(cur_sol)) opts2 = opts opts2 = opts2[:i] + opts2[i+1:] self.get_permute(opts2, cur_sol) cur_sol.pop() def numTilePossibilities(self, tiles: str) -> int: self.solutions = set() self.get_permute(tiles, []) return len(self.solutions)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
# This is a mathematical problem. # Get the frequencies of different characters [f_0, f_1, ..., f_n]. # For each possible choice of frequency [i_0, i_1, ..., i_n] (0 <= i_k <= f_k, k = 0, 1, ..., n), # the number of distinct sequences is (i_0 + i_1 + ... + i_n)! / ( i_0! * i_1! * ... * i_n!). # To get numbers of occurrences you can just run # freq = count.values() # for this problem you only need to iterate over freq, so you don't even need to convert it to list. # Kind of depends on your taste, but for calculating digits you have the option of using divmod: # for f in freq: # i, mod = divmod(i, f + 1) # digits.append(mod) import collections, math class Solution: def numTilePossibilities(self, tiles: str) -> int: freq = collections.Counter(tiles) prod = 1 for f in freq.values(): prod *= f + 1 res = 0 for i in range(1, prod): digits = [] for f in freq.values(): digits.append(i % (f + 1)) i = i // (f + 1) tmp = math.factorial(sum(digits)) for d in digits: tmp //= math.factorial(d) res += tmp return res
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: result = set() vis = [0]*len(tiles) def dfs(res,depth): if res: result.add(res) if depth == len(tiles)-1: result.add(res) for i in range(len(tiles)): if not vis[i]: vis[i] = 1 dfs(res+tiles[i],depth+1) vis[i] = 0 dfs('',-1) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def solve(s,visited): seen.add(s) if len(s) == len(tiles):return 0 for i , v in enumerate(tiles): if i not in visited: solve(s + v,visited | {i}) return len(seen) seen = set() return solve('',set()) - 1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: result = set() def dfs_helper(path, t): if path: result.add(path) for i in range(len(t)): dfs_helper(path + t[i], t[:i] + t[i+1:]) dfs_helper('',tiles) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: ans = 0 s = set() def tot(curr, rem): nonlocal s if curr[-1]: s.add(tuple(curr[-1])) for i in range(len(rem)): el = curr[-1] if rem[i] == el: continue tot(curr+[el + [rem[i]]], rem[:i] + rem[i+1:]) tot([[]], tiles) return len(s)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def subsets(self, tiles, buff, buff_index, boolean, s): if tuple(buff[:buff_index]) not in s: # print(buff[:buff_index]) s.add(tuple(buff[:buff_index])) self.count += 1 if len(buff) == buff_index: return for i in range(0, len(tiles)): if not boolean[i]: buff[buff_index] = tiles[i] boolean[i] = True self.subsets(tiles, buff, buff_index+1, boolean, s) boolean[i] = False def numTilePossibilities(self, tiles: str) -> int: self.count = 0 buff = [None]*len(tiles) boolean = [False]*len(tiles) s = set() self.subsets(tiles, buff, 0, boolean, s) return self.count-1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles): res=set() def helper(t,curr,k): if k==len(curr): res.add(curr) return # return so that the loop below doesn't continue when you meet the length requirement for i in range(len(t)): # call helper with everything but the current value helper(t[:i]+t[i+1:], curr+t[i], k) # start at size 1 and move until size len(tiles), +1 because range doesn't include the endpoint for i in range(1,len(tiles)+1): helper(tiles,'',i) return((len(res)))
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def make_tile(self, curr, used, letters, size): if len(curr) == size: # print(curr) self.res += 1 return i = 0 while i < len(letters): if i not in used: used.add(i) curr.append(letters[i]) self.make_tile(curr, used, letters, size) curr.pop(-1) used.remove(i) while i + 1 < len(letters) and letters[i] == letters[i + 1]: i += 1 i += 1 def numTilePossibilities(self, tiles: str) -> int: self.res = 0 letters = sorted(tiles) for size in range(1, len(tiles) + 1): self.make_tile([], set(), letters, size) return self.res
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def next_permutation(a): for i in range(len(a) - 1, 0, -1): if a[i] > a[i - 1]: ps = i for j in range(i + 1, len(a)): if a[j] > a[i - 1] and a[ps] > a[j]: ps = j a[ps], a[i - 1] = a[i - 1], a[ps] p1 = i p2 = len(a) - 1 while p1 < p2: a[p1], a[p2] = a[p2], a[p1] p1 += 1 p2 -= 1 return True return False n = 1 for i in range(1, len(tiles) + 1): n *= i a = set() perm = [] for i in range(len(tiles)): perm.append(i) for _ in range(n): cur = '' for i in range(len(tiles)): cur += tiles[perm[i]] for i in range(len(tiles)): a.add(cur[:i + 1]) next_permutation(perm) return len(a)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
from collections import Counter class Solution: def __init__(self): self.sum_ = 0 def recurse_count(self, letter_count): if len(letter_count)==0: return for letter in letter_count: self.recurse_count(letter_count - Counter(letter)) self.sum_ += 1 return def numTilePossibilities(self, tiles: str) -> int: letter_count = Counter(tiles) self.recurse_count(letter_count) return self.sum_
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def recur(tiles): if not tiles: return set() ans = set() temp = '' while tiles: v = tiles[0] ans.add(v) new = recur(temp+tiles[1:]) ans.update(new) for k in new: ans.add(v+k) temp+=tiles[0] tiles = tiles[1:] return ans ans = recur(tiles) # print(ans) return len(ans)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: #sequence can be of length 0 to len(tiles) result = set() def backtrack(left_tiles, curr_seq):#k is our desired length if len(curr_seq) == k:#reached our desired length result.add(''.join(curr_seq)) return else: for i in range(len(left_tiles)): curr_seq.append(left_tiles[i]) backtrack(left_tiles[:i] + left_tiles[i+1:], curr_seq) curr_seq.pop() for k in range(1, len(tiles)+1): backtrack(tiles, []) return len(result)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def recur(tiles): if not tiles: return set() ans = set() for i,v in enumerate(tiles): ans.add(v) new = recur(tiles[:i]+tiles[i+1:]) ans.update(new) for k in new: ans.add(v+k) return ans ans = recur(tiles) # print(ans) return len(ans)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def counts(self, collect): answer = 1 for char in collect: if collect[char]: answer += self.counts(collect - collections.Counter(char)) return answer def numTilePossibilities(self, c): return self.counts(collections.Counter(c)) - 1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: tiles = ''.join(sorted(tiles)) memo = {} def helper(s, k): if (s, k) not in memo: if k == 0: memo[(s,k)] = 1 else: last, ans = '', 0 for i in range(len(s)): if s[i] != last: last = s[i] ans += helper(s[:i]+s[i+1:], k-1) memo[(s,k)] = ans return memo[(s,k)] ret = 0 for k in range(1, len(tiles)+1): ret += helper(tiles, k) return ret
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def perm(k, a): if k == 0: return [] elif k == 1: return [x for x in a] else: return [a[i] + y for i in range(len(a)) for y in perm(k-1, a[:i] + a[i+1:])] out = set() for i in range(1, len(tiles)+1): for x in perm(i, tiles): out.add(x) return len(out) # complexity: N = len(t), N*N! # space complexity: O(N!)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
from collections import Counter class Solution: def numTilePossibilities(self, tiles: str) -> int: counter = Counter(tiles) def dfs(counter): result = len(counter) print(result) for character in counter: temp = counter.copy() if temp[character] == 1: del temp[character] else: temp[character] -= 1 result += dfs(temp) return result result = dfs(counter) return result
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: output = set() def helper(result, options): if not options: return for idx, o in enumerate(options): tmp = options[:] tmp.pop(idx) output.add(''.join(result + [o])) helper(result + [o], tmp) helper([], list(tiles)) return len(output)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def helper(curr, tiles): for i in range(len(tiles)): curr.append(tiles[i]) pos.add(str(curr)) c = tiles.copy() c.pop(i) helper(curr.copy(), c) curr.pop() tiles = list(tiles) pos = set() helper([], tiles) return len(pos)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def poss(self, tiles:str) -> set: if len(tiles) == 1: return set([tiles[0]]) output = set() for i in range(len(tiles)): elem = tiles[i] res = self.poss(tiles[:i]+tiles[i+1:]) output = output.union(res) for elem in res: output.add(tiles[i]+elem) return output def numTilePossibilities(self, tiles: str) -> int: if len(tiles) == 0: return 0 return len(self.poss(tiles))
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: seen = set() ans = set() def backtrack(tiles,seen,curr): if curr != '' and curr not in ans: ans.add(curr) for i in range(len(tiles)): if i not in seen: seen.add(i) backtrack(tiles,seen,curr+tiles[i]) seen.remove(i) backtrack(tiles,seen,'') return len(ans)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
from itertools import permutations class Solution: def numTilePossibilities(self, tiles: str) -> int: total = 0 for size in range(1, len(tiles) + 1): total += len(set(permutations(tiles, size))) return total
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: def backtrack(i, c): if i == n: return for k in c: if c[k] > 0: self.ans += 1 backtrack(i + 1, c - Counter(k)) n = len(tiles) counter = Counter(tiles) self.ans = 0 backtrack(0, counter) return self.ans
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def __init__(self): self.res = set() def backtrack(self,tiles,curr,indices): for i in range(len(tiles)): if i not in set(indices): curr+=tiles[i] indices.append(i) self.res.add(curr) if len(curr)<len(tiles): self.backtrack(tiles,curr,indices) curr = curr[:-1] indices.pop() def numTilePossibilities(self, tiles: str) -> int: self.backtrack(tiles,'',[]) return len(self.res)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
def possible(tiles): variants = set() if len(tiles) == 1: variants.add(tiles[0]) else: for i in range(len(tiles)): t = possible(tiles[:i]+tiles[i+1:]) variants.update(t) for j in t: variants.add(tiles[i]+j) return variants class Solution: def numTilePossibilities(self, tiles: str) -> int: return len(possible(tiles))
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
from itertools import combinations as C class Solution: def numTilePossibilities(self, tiles: str) -> int: num = 0 for i in range(1, len(tiles)+1): l = set(permutations(tiles, i)) num += len(l) return num
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: if len(tiles) < 2: return len(tiles) nodes = [] for letter in tiles: nodes.append(Node(letter)) for node in nodes: for other_node in nodes: if node != other_node: node.edges.append(other_node) paths = set() seen = set() for node in nodes: self.backtrack(node, seen, node.char, paths) print(paths) return len(paths) def backtrack(self, node, seen: set, path: str, paths: set): if node in seen: return path += node.char if path and path not in paths: paths.add(path) for neighbor in node.edges: seen.add(node) self.backtrack(neighbor, seen, path, paths) seen.remove(node) class Node: def __init__(self, char: str): self.char = char self.edges = []
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: possibilities = set() def swap(arr, l, r): if l == r: return arr[l], arr[r] = arr[r], arr[l] def add_permutation(arr): nonlocal possibilities for i in range(len(arr)): possibilities.add(''.join(arr[:i+1])) def build_permutations(arr, start = 0): if start >= len(arr): add_permutation(arr) return for i in range(start, len(arr)): swap(arr, i, start) build_permutations(arr, start + 1) swap(arr, i, start) build_permutations(list(tiles)) return len(possibilities)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: if len(tiles) < 2: return len(tiles) nodes = [] for letter in tiles: nodes.append(Node(letter)) for node in nodes: for other_node in nodes: if node != other_node: node.edges.append(other_node) paths = set() seen = set() for node in nodes: self.backtrack(node, seen, node.char, paths) return len(paths) def backtrack(self, node, seen: set, path: str, paths: set): if node in seen: return path += node.char if path and path not in paths: paths.add(path) for neighbor in node.edges: seen.add(node) self.backtrack(neighbor, seen, path, paths) seen.remove(node) class Node: def __init__(self, char: str): self.char = char self.edges = []
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: count=0 for i in range(1,len(tiles)+1): count+=len(set(permutations(tiles,i))) return count
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: result = 0 def numTilePossibilities(self, tiles: str) -> int: counter = Counter(tiles) self.dfs(counter, []) return self.result def dfs(self, counter, curr): if curr: self.result += 1 for x in counter: curr1 = curr.copy() counter1 = counter.copy() curr1.append(x) counter1[x] -= 1 if counter1[x] == 0: del counter1[x] self.dfs(counter1, curr1)
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, s: str) -> int: ans, C = 0, Counter(s) def dfs(C, cur): nonlocal ans if cur: ans += 1 if not C: return C1 = C.copy() for x in C: cur.append(x); C1[x] -= 1 if C1[x] == 0: del C1[x] dfs(C1, cur) cur.pop(); C1[x] += 1 dfs(C, cur=[]) return ans
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: memos = dict() def numTilePossibilities(self, tiles: str) -> int: tiles = ''.join(sorted(tiles)) uniques = self.step(tiles) return len(uniques) - 1 def step(self, tiles: str) -> set: if len(tiles) == 0: return {''} if tiles not in self.memos: uniques = set() for i in range(len(tiles)): c = tiles[i] substr = tiles[:i] + tiles[i + 1:] substrs_set = self.step(substr) for substr in substrs_set: uniques.add(substr) for j in range(len(substr) + 1): new_str = substr[:j] + c + substr[j:] uniques.add(new_str) self.memos[tiles] = uniques return self.memos[tiles]
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
class Solution: def numTilePossibilities(self, tiles: str) -> int: res = set() def seq(s, l): if len(l) == 0: res.add(s) return seq(s, l[1 : ]) for i in range(len(l)): seq(s + l[i], l[ : i] + l[i + 1 : ]) seq('', list(tiles)) return len(res) - 1
You have n  tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
from collections import Counter class Solution: def numTilePossibilities(self, tiles: str) -> int: def permutation(num, tiles_counter): if num == 1: return len(list(tiles_counter)) rs = 0 for c in +tiles_counter: rs += permutation(num-1, tiles_counter - Counter({c:1})) return rs total = 0 for i in range(1, len(tiles) + 1): total += permutation(i, Counter(tiles)) return total
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution: def multiply(self,num1, num2): """ :type num1: str :type num2: str :rtype: str """ a=['0','1','2','3','4','5','6','7','8','9'] z=0 x=0 for i,element in enumerate(num1): for j in range(10): if element==a[j]: z+=j*(10**(len(num1)-i-1)) for c,b in enumerate(num2): for k in range(10): if b==a[k]: x+=k*(10**(len(num2)-c-1)) mul=z*x return(''.join('%d'%mul))
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution: def multiply(self,num1, num2): """ :type num1: str :type num2: str :rtype: str """ a=['0','1','2','3','4','5','6','7','8','9'] z=0 x=0 for i,element in enumerate(num1): for j in range(10): if element==a[j]: z+=j*(10**(len(num1)-i-1)) for c,b in enumerate(num2): for k in range(10): if b==a[k]: x+=k*(10**(len(num2)-c-1)) mul=z*x return(''.join('%d'%mul))
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6" Example 2: Input: num1 = "123", num2 = "456" Output: "56088" Note: The length of both num1 and num2 is < 110. Both num1 and num2 contain only digits 0-9. Both num1 and num2 do not contain any leading zero, except the number 0 itself. You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution: def multiply(self,num1, num2): a=['0','1','2','3','4','5','6','7','8','9'] z=0 x=0 for i,element in enumerate(num1): for j in range(10): if element==a[j]: z+=j*(10**(len(num1)-i-1)) for c,b in enumerate(num2): for k in range(10): if b==a[k]: x+=k*(10**(len(num2)-c-1)) mul=z*x return(''.join('%d'%mul))
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be: 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1]) 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1]) 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j]) 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j]) Notice that there could be some invalid signs on the cells of the grid which points outside the grid. You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest. You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only. Return the minimum cost to make the grid have at least one valid path.   Example 1: Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] Output: 3 Explanation: You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. Example 2: Input: grid = [[1,1,3],[3,2,2],[1,1,4]] Output: 0 Explanation: You can follow the path from (0, 0) to (2, 2). Example 3: Input: grid = [[1,2],[4,3]] Output: 1 Example 4: Input: grid = [[2,2,2],[2,2,2]] Output: 3 Example 5: Input: grid = [[4]] Output: 0   Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 100
from collections import deque class Solution: def minCost(self, grid: List[List[int]]) -> int: right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0) direction_map = { 1: right, 2: left, 3: down, 4: up } directions = [right, left, down, up] visited = set() def in_bounds(i, j): return 0 <= i < len(grid) and 0 <= j < len(grid[i]) def dfs(i, j): # not in bounds if not in_bounds(i, j) or (i, j) in visited: return [] visited.add((i, j)) sign = grid[i][j] direction = direction_map[sign] next_i, next_j = i + direction[0], j + direction[1] return [(i, j)] + dfs(next_i, next_j) reachable = dfs(0, 0) curr_cost = 0 while reachable: next_reachable = [] for (i, j) in reachable: if i == len(grid) - 1 and j == len(grid[i]) - 1: return curr_cost for d in directions: next_reachable += dfs(i + d[0], j + d[1]) reachable = next_reachable curr_cost += 1 return -1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: def dp(i, j): if i==0: return 2*j # if j==0: return 0 if j==1: return 2 if (i, j) in memo: return memo[(i, j)] base = x**i q, r = divmod(j, base) if r==0: return q*i memo[(i, j)]=min(q*i+dp(i-1, r), (q+1)*i+dp(i-1, base-r)) return memo[(i, j)] memo = {} return dp(ceil(log(target, x)), target)-1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: @lru_cache(None) def calc(goal): if x == goal: return 0 if x > goal: return min(goal*2 - 1, (x - goal) * 2) sums = x times = 0 while sums < goal: times += 1 sums *= x if sums == goal: return times if sums - goal < goal: return min(calc(sums - goal) + times + 1, calc(goal - (sums // x)) + times) return calc(goal - (sums // x)) + times return calc(target)
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
from functools import lru_cache class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: @lru_cache(None) def search(t: int) -> int: if x == t: return 0 if t < x: d1, d2 = t, x - t return min(2 * d1 - 1, 2 * d2) k1 = int(math.log(t, x)) y1 = x ** k1 if y1 == t: return k1 - 1 total = k1 + search(t - y1) k2 = k1 + 1 y2 = x ** k2 if y2 <= 2 * t - y1: total = min(total, k2 + search(y2 - t)) return total return search(target)
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: q, s = [], set() q.append((0, target)) while q: c, t = heapq.heappop(q) if t == 0: return c - 1 if t in s: continue s.add(t) n = int(log(t) / log(x)) l = t - x**n heapq.heappush(q, (c+(2 if n==0 else n), l)) r = x**(n+1) - t heapq.heappush(q, (c + n + 1, r))
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: import math from functools import lru_cache @lru_cache(maxsize=None) def f(x, target, depth): # print(' ' * depth, '开始计算', x, target) if target == 1: return 1 res = target * 2 - 1 if target < x: if x - target < target: res = min(res, 1 + f(x, x - target, depth + 1)) else: y = math.log(target, x) y_lower = int(y) p = pow(x, y_lower) cnt = target // p remain = target - cnt * p if y > y_lower: res = min(res, y_lower * cnt + f(x, remain, depth + 1)) if p * x - target < target: res = min(res, y_lower + 1 + f(x, p * x - target, depth + 1)) else: res = y_lower - 1 return res return f(x, target, 0)
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x, y): pos = neg = k = 0 while y: y, cur = divmod(y, x) if k: pos, neg = min(cur * k + pos, (cur + 1) * k + neg), min((x - cur) * k + pos, (x - cur - 1) * k + neg) else: pos, neg = cur * 2, (x - cur) * 2 k += 1 return min(pos, k + neg) - 1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: cost = list(range(40)) cost[0] = 2 from functools import lru_cache @lru_cache(None) def dp(i, target) : if target == 0 : return 0 if target == 1 : return cost[i] if i >= 39 : return float('inf') t, r = divmod(target, x) return min(r * cost[i] + dp(i + 1, t), (x - r) * cost[i] + dp(i + 1, t + 1)) return dp(0, target) - 1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: cost = list(range(32)) cost[0] = 2 from functools import lru_cache @lru_cache(None) def dp(i, target) : if target == 0 : return 0 if target == 1 : return cost[i] if i >= 31 : return float('inf') t, r = divmod(target, x) return min(r * cost[i] + dp(i + 1, t), (x - r) * cost[i] + dp(i + 1, t + 1)) return dp(0, target) - 1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
from functools import lru_cache class Solution: @lru_cache(None) def leastOpsExpressTarget(self, x: int, target: int) -> int: if x == target: return 0 if x > target: return min(target*2-1,(x-target)*2) sums, cnt = x, 0 while sums < target: sums *= x cnt += 1 if sums == target: return cnt left, right = float('inf'), float('inf') if sums - target < target: right = self.leastOpsExpressTarget(x, sums-target) + cnt + 1 left = self.leastOpsExpressTarget(x, target-sums//x) + cnt return min(left,right)
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: dp = {} def dfs(i, target): if i in dp and target in dp[i]: return dp[i][target] if target == 0: return 0 if i >= 32: return float('inf') div = x ** i res = target % div ret = min(dfs(i + 1, target - res) + res * x // div * (i - 1), dfs(i + 1, target - res + div) + (div - res) * x // div * (i - 1)) if res == 0: ret = min(ret, target // div * i) dp[i] = dp.get(i, {}) dp[i][target] = ret return ret res = target % x return min(dfs(2, target - res) + res * 2, dfs(2, target - res + x) + (x - res) * 2) - 1
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. When writing such an expression, we adhere to the following conventions: The division operator (/) returns rational numbers. There are no parentheses placed anywhere. We use the usual order of operations: multiplication and division happens before addition and subtraction. It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation. We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.   Example 1: Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations. Example 2: Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations. Example 3: Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.   Note: 2 <= x <= 100 1 <= target <= 2 * 10^8
# from functools import lru_cache class Solution: def leastOpsExpressTarget(self, x: int, target: int) -> int: cost = list(range(40)) cost[0] = 2 @lru_cache(None) def dp(i, targ): if targ == 0: return 0 if targ == 1: return cost[i] if i >= 39: return float('inf') t, r = divmod(targ, x) return min(r * cost[i] + dp(i+1, t), (x-r) * cost[i] + dp(i+1, t+1)) return dp(0, target) - 1
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A, B): # Optimization #commons = set(A).intersection(set(B)) # or commons = set(A) & set(B) #A = [x for x in A if x in commons] #B = [x for x in B if x in commons] N1, N2 = len(A), len(B) dp = [[0 for _ in range(N2+1)] for _ in range(N1+1)] for i1, v1 in enumerate(A, start = 1): for i2, v2 in enumerate(B, start = 1): if v1 == v2: dp[i1][i2] = dp[i1-1][i2-1] + 1 else: dp[i1][i2] = max(dp[i1-1][i2], dp[i1][i2-1]) return dp[N1][N2] class Solution: def maxUncrossedLines(self, A, B): commons = set(A).intersection(set(B)) # or commons = set(A) & set(B) A = [x for x in A if x in commons] B = [x for x in B if x in commons] N1, N2 = len(A), len(B) dp = [0 for _ in range(N2+1)] for i1, v1 in enumerate(A, start = 1): tmp = [0 for _ in range(N2+1)] for i2, v2 in enumerate(B, start = 1): if v1 == v2: tmp[i2] = dp[i2-1] + 1 else: tmp[i2] = max(dp[i2], tmp[i2-1]) dp = tmp return dp[N2] from collections import defaultdict class Solution: def maxUncrossedLines(self, A, B): f = defaultdict(list) for idx, val in enumerate(B): f[val].insert(0, idx) dp = [0] * len(B) for val in A: for j in f[val]: dp[j] = max(dp[j], max(dp[:j], default=0) + 1) return max(dp)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = [0] * len(B) d = {} for i in range(len(B)): b = B[i] if b in d: d[b].append(i) else: d[b] = [i] for a in A: if a in d: for k in d[a][::-1]: if k == 0: dp[k] = 1 else: dp[k] = dp[k - 1] + 1 for i in range(k + 1, len(dp)): if dp[i] < dp[i - 1]: dp[i] = dp[i - 1] else: break # print(dp) return max(dp)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: memo = defaultdict(list) for i, n in enumerate(B): memo[n].append(i) @lru_cache(None) def helper(index, taken): if index >= len(A): return 0 count = 0 if A[index] in memo: for i in memo[A[index]]: if i > taken: count = 1 + helper(index+1, i) break count = max(count, helper(index+1, taken)) return count return helper(0, -1)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: memo = {} def helper(a_idx, b_idx): if (a_idx, b_idx) in memo: return memo[(a_idx, b_idx)] if a_idx == len(A) or b_idx == len(B): return 0 c1 = 0 if A[a_idx] == B[b_idx]: c1 = 1 + helper(a_idx + 1, b_idx + 1) c2 = helper(a_idx + 1, b_idx) c3 = helper(a_idx, b_idx + 1) memo[(a_idx, b_idx)] = max(c1, c2, c3) return memo[(a_idx, b_idx)] return helper(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = {} def func(indexA, indexB): if indexA == len(A) or indexB == len(B): return 0 if (indexA,indexB) in dp: return dp[indexA,indexB] if A[indexA] == B[indexB]: dp[indexA,indexB] = func(indexA + 1, indexB + 1) + 1 else: dp[indexA,indexB] = max(func(indexA + 1, indexB),func(indexA, indexB + 1)) return dp[indexA,indexB] return func(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
from collections import defaultdict from functools import lru_cache class Solution: @lru_cache(None, False) def solve(self, a_from: int, b_from: int): if a_from >= len(self.A) or b_from >= len(self.B): return 0 else: max_line = 0 for b_pos in self.b_index[self.A[a_from]]: if b_pos >= b_from: if_draw = 1 + self.solve(a_from+1, b_pos+1) max_line = max(max_line, if_draw) max_line = max(self.solve(a_from+1, b_from), max_line) return max_line def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: self.A = A self.B = B self.b_index = defaultdict(list) for i, b in enumerate(B): self.b_index[b].append(i) return self.solve(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: def help(i, j, mem): if i>=len(A) or j>=len(B): return 0 if (i,j) in mem: return mem[(i,j)] if A[i]==B[j]: mem[(i, j)] = 1 + help(i+1, j+1, mem) return mem[(i,j)] mem[(i, j)] = max(help(i+1, j, mem), help(i, j+1, mem)) return mem[(i, j)] mem = {} return help(0, 0, mem)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: return self.findMaxConnectLines(0, 0, A, B, {}) def findMaxConnectLines(self, i, j, A, B, dic): if i == len(A) or j == len(B): return 0 if (i, j) in dic: return dic[(i, j)] a = self.findMaxConnectLines(i+1, j, A, B, dic) b = float('-inf') for k in range(j, len(B)): if B[k] == A[i]: b = self.findMaxConnectLines(i+1, k+1, A, B, dic) + 1 break dic[(i, j)] = max(a, b) return dic[(i, j)] # 1, 4, 2 ,3, 5 # 1, 2, 3, 5, 4 # every number has choices: not connect or connect (first encounter connect) #
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: memo = {} return self.helper(0,0,A,B,memo) def helper(self,a_index,b_index,A,B,memo): if a_index == len(A) or B == len(B): return 0 elif (a_index,b_index) in memo: return memo[(a_index,b_index)] else: put_ = 0 noput_ = 0 for i in range(b_index,len(B)): if B[i] == A[a_index]: put_ = 1 + self.helper(a_index + 1,i + 1,A,B,memo) break noput_ = self.helper(a_index + 1,b_index,A,B,memo) memo[(a_index,b_index)] = max(put_,noput_) return memo[(a_index,b_index)]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: memo = {} def helper(a_idx, b_idx): if a_idx == len(A) or b_idx == len(B): return 0 if (a_idx, b_idx) in memo: return memo[(a_idx, b_idx)] c1 = 0 if A[a_idx] == B[b_idx]: c1 = 1 + helper(a_idx + 1, b_idx + 1) c2 = helper(a_idx + 1, b_idx) c3 = helper(a_idx, b_idx + 1) memo[(a_idx, b_idx)] = max(c1, c2, c3) return memo[(a_idx, b_idx)] return helper(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: b_dict = {} for idx, b in enumerate(B): if b not in b_dict: b_dict[b] = [] b_dict[b].append(idx) a_ptrs = [] for key in b_dict: b_dict[key].reverse() for a in A: if a in b_dict: a_ptrs = a_ptrs + b_dict[a] lis = [] for idx, a in enumerate(a_ptrs): lis_len = 0 for i in reversed(range(idx)): if a_ptrs[i] < a: lis_len = max(lis_len, lis[i]) lis_len += 1 lis.append(lis_len) if len(lis) == 0: return 0 return max(lis)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: if len(A)>len(B): A, B=B, A DP=[0]* (len(A)+1) coll={j:[-1]+[i for i in range(len(A)) if A[i]==j] for j in set(B)} for iB in B[::-1]: for i in range(1, len(coll[iB])): DP[coll[iB][i]] = max(DP[coll[iB][i]], DP[coll[iB][i]+1]+1) for j in range(coll[iB][i], coll[iB][i-1], -1): DP[j]=max(DP[j], DP[j+1]) return DP[0]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
def longest_substr(A, B, i, j, cache): if i == len(A) or j == len(B): return 0 res = cache.get(i, {}).get(j, None) if res is not None: return res length1 = 0 if A[i] == B[j]: length1 = 1 + longest_substr(A, B, i + 1, j + 1, cache) length2 = longest_substr(A, B, i + 1, j, cache) length3 = longest_substr(A, B, i, j + 1, cache) length = max(length1, length2, length3) cache[i][j] = length return length class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: cache = defaultdict(dict) return longest_substr(A, B, 0, 0, cache)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: from bisect import bisect a, b = len(A), len(B) indA = defaultdict(list) indB = defaultdict(list) for i,num in enumerate(A): indA[num].append(i) for i,num in enumerate(B): indB[num].append(i) dp = {} for i, num1 in enumerate(A): for j, num2 in enumerate(B): if num1 == num2: dp[(i,j)] = 1 + (dp[(i-1,j-1)] if min(i,j) > 0 else 0) else: ii = bisect(indB[num1], j) if num1 in indB else 0 jj = bisect(indA[num2], i) if num2 in indA else 0 iii = -1 if ii == 0 else indB[num1][ii-1] jjj = -1 if jj == 0 else indA[num2][jj-1] dp[i,j] = dp[i-1,j-1] if min(i,j)>0 else 0 if iii >= 0: dp[i,j] = max(dp[i,j], 1+dp[i-1,iii-1] if min(i,iii)>0 else 1) if jjj >= 0: dp[i,j] = max(dp[i,j], 1+dp[jjj-1,j-1] if min(j,jjj)>0 else 1) return dp[a-1,b-1]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = collections.defaultdict(int) m, n = len(A), len(B) for x in range(m): for y in range(n): cur = 0 if A[x] == B[y]: cur = 1 dp[(x, y)] = max(dp[(x - 1, y - 1)] + cur, dp[(x - 1, y)], dp[(x, y - 1)]) return dp[(m - 1, n - 1)]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def fonction(self, a, b, i, j, dp): if j==len(b) or i==len(a): return 0 if dp[i][j]!=-1: return dp[i][j] if a[i]==b[j]: dp[i][j] = 1+self.fonction(a,b,i+1,j+1,dp) return dp[i][j] dp[i][j] = max(self.fonction(a,b,i+1,j+1,dp),self.fonction(a,b,i,j+1,dp),self.fonction(a,b,i+1,j,dp)) return dp[i][j] def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = [] for i in range(len(A)): dp.append([-1] * len(B)) return self.fonction(A,B,0,0,dp)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def build_value_index_map(self,arr): value_idx_map = collections.defaultdict(list) for i in range(len(arr)): value_idx_map[arr[i]].append(i) return value_idx_map def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: b_value_idx_map = self.build_value_index_map(B) memo = {} def helper(a_idx,b_max_idx,memo): if a_idx == len(A) or b_max_idx == len(B): return 0 if (a_idx,b_max_idx) in memo: return memo[a_idx,b_max_idx] curr_num = A[a_idx] res = 0 for b_idx in b_value_idx_map.get(curr_num,[]): if b_idx > b_max_idx: temp = 1 + helper(a_idx+1,b_idx,memo) res = max(res,temp) memo[a_idx,b_max_idx] = max(res,helper(a_idx+1,b_max_idx,memo)) return memo[a_idx,b_max_idx] res= helper(0,-1,memo) return res
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: m, n = len(A), len(B) if m == 0 or n == 0: return 0 memo = dict() def dfs(i, j): if i == m or j == n: return 0 if (i, j) in memo: return memo[(i, j)] res = max(dfs(i+1, j), dfs(i, j+1)) if A[i] == B[j]: res = max(res, 1 + dfs(i+1, j+1)) memo[(i, j)] = res return res return dfs(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: B_index = collections.defaultdict(list) for i in range(len(B)): B_index[B[i]].append(i) memory = {} def helper(A_i_, B_i): A_i = A_i_ if (A_i, B_i) in memory: return memory[(A_i, B_i)] while A_i < len(A): # check A match with B: if A[A_i] in B_index: for b_i in B_index[A[A_i]]: if b_i < B_i: continue res = max(1 + helper(A_i+1, b_i+1), helper(A_i+1, B_i)) memory[(A_i_, B_i)] = res return res A_i += 1 memory[(A_i_, B_i)] = 0 return 0 return helper(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: cache = {} def recur(A,B,i,j): key = str(i) + '$' + str(j) if key in cache: return cache[key] if i >= len(A) or j >= len(B): cache[key] = 0 return cache[key] if A[i] == B[j]: cache[key] = 1 + recur(A,B, i + 1, j + 1) else: cache[key] = max(recur(A,B, i + 1, j), recur(A,B,i,j + 1)) return cache[key] return recur(A,B,0,0);
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: m, n = len(A), len(B) dp = [[0] * (n+1) for _ in range(m+1)] for i in range(1,m+1): for j in range(1,n+1): left = dp[i][j-1] up = dp[i-1][j] leftup = dp[i-1][j-1] dp[i][j] = max(left, up, leftup + int(A[i-1]==B[j-1])) print(left, up, leftup) return dp[m][n]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = [] for i in range(len(A)): dp.append([0] * len(B)) for i in range(len(A)): for j in range(len(B)): if A[i] == B[j]: dp[i][j] = max(dp[i][j],1) if i - 1 >= 0 and j - 1 >= 0 : dp[i][j] = max(dp[i][j],dp[i-1][j-1]+1) else: if i - 1 >= 0 and j - 1 >= 0: dp[i][j] = max(dp[i][j],dp[i-1][j-1]) if j - 1 >= 0: dp[i][j] = max(dp[i][j],dp[i][j-1]) if i - 1 >= 0: dp[i][j] = max(dp[i][j],dp[i-1][j]) return dp[-1][-1]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: @lru_cache(None) def helper(i: int, j: int) -> int: if i < 0 or j < 0: return 0 return max([ helper(i - 1, j - 1) + (A[i] == B[j]), helper(i - 1, j), helper(i, j - 1) ]) return helper(len(A) - 1, len(B) - 1)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: m, n = len(A), len(B) dp = [[0] * n for _ in range(m)] # dp[0][0] = int(A[0] == B[0]) for i in range(m): for j in range(n): left = dp[i][j-1] if j>0 else 0 up = dp[i-1][j] if i>0 else 0 leftup = dp[i-1][j-1] if i>0 and j>0 else 0 dp[i][j] = max(left, up, leftup + int(A[i]==B[j])) print(left, up, leftup) return dp[m-1][n-1]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
from collections import defaultdict class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: dp = [[0] * (len(B) + 1) for _ in range(len(A) + 1)] vals_A = defaultdict(list) for i in range(len(A)): vals_B = defaultdict(list) for j in range(len(B)): dp[i + 1][j + 1] = max(dp[i][j], dp[i + 1][j], dp[i][j + 1]) if A[i] == B[j]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1) for pos in vals_A[B[j]]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[pos][j] + 1) for pos in vals_B[A[i]]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][pos] + 1) vals_B[B[j]] += [j] vals_A[A[i]] += [i] return dp[len(A)][len(B)]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
from collections import defaultdict class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: if len(A) < len(B): A, B = B, A dp = [[0] * (len(B) + 1) for _ in range(len(A) + 1)] vals_A = defaultdict(list) for i in range(len(A)): vals_B = defaultdict(list) for j in range(len(B)): dp[i + 1][j + 1] = max(dp[i][j], dp[i + 1][j], dp[i][j + 1]) if A[i] == B[j]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1) for pos in vals_A[B[j]]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[pos][j] + 1) for pos in vals_B[A[i]]: dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][pos] + 1) vals_B[B[j]] += [j] vals_A[A[i]] += [i] return dp[len(A)][len(B)]
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
from collections import defaultdict class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: memo = {} def r_search(aindex, bindex): if aindex == len(A) or bindex == len(B): return 0 if (aindex, bindex) in memo: return memo[(aindex, bindex)] best = 0 best = max(best, r_search(aindex + 1, bindex)) best = max(best, r_search(aindex, bindex + 1)) if A[aindex] == B[bindex]: best = max(best, r_search(aindex + 1, bindex + 1) + 1) memo[(aindex, bindex)] = best return best return r_search(0, 0)
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: # self.res = float('-inf') self.A, self.B = A, B self.seen = {} return self.dfs(0, 0) def dfs(self, a, b): m, n = len(self.A), len(self.B) if a >= m or b >= n: return 0 if (a, b) in self.seen: return self.seen[(a, b)] res = float('-inf') cur_b = b if self.A[a] == self.B[b]: res = max(res, self.dfs(a + 1, b + 1) + 1) # while cur_b < n: # if self.A[a] == self.B[cur_b]: # res = max(res, self.dfs(a + 1, cur_b + 1) + 1) # break # cur_b += 1 # cur_a = a # while cur_a < m: # # print(cur_a, b) # if self.A[cur_a] == self.B[b]: # res = max(res, self.dfs(cur_a + 1, b + 1) + 1) # break # cur_a += 1 res = max(res, self.dfs(a + 1, b)) res = max(res, self.dfs(a, b + 1)) self.seen[(a, b)] = res return res
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: # self.res = float('-inf') self.A, self.B = A, B self.seen = {} return self.dfs(0, 0) def dfs(self, a, b): if a >= len(self.A) or b >= len(self.B): return 0 if (a, b) in self.seen: return self.seen[(a, b)] res = float('-inf') if self.A[a] == self.B[b]: res = max(res, self.dfs(a + 1, b + 1) + 1) res = max(res, self.dfs(a + 1, b)) res = max(res, self.dfs(a, b + 1)) self.seen[(a, b)] = res return res
We write the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that: A[i] == B[j]; The line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line. Return the maximum number of connecting lines we can draw in this way.   Example 1: Input: A = [1,4,2], B = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2. Example 2: Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] Output: 3 Example 3: Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] Output: 2   Note: 1 <= A.length <= 500 1 <= B.length <= 500 1 <= A[i], B[i] <= 2000
class Solution: def getMaxUncrossedLinesFrom(self, A, B, min_a_ix, min_b_ix): max_count = 0 key = (min_a_ix, min_b_ix) if key in self.cache: return self.cache[key] for i_a in range(min_a_ix, len(A)): val_a = A[i_a] b_match_indexes = self.b_lookup.get(val_a) if not b_match_indexes: continue for b_ix in b_match_indexes: if b_ix >= min_b_ix: ct = 1 + self.getMaxUncrossedLinesFrom(A, B, i_a + 1, b_ix + 1) max_count = max(max_count, ct) self.cache[key] = max_count return max_count def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: b_lookup = defaultdict(list) for i, n in enumerate(B): b_lookup[n].append(i) self.b_lookup = b_lookup self.cache = {} return self.getMaxUncrossedLinesFrom(A, B, 0, 0)