活跃农民
- 积分
- 993
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-11-6
- 最后登录
- 1970-1-1
|
本帖最后由 ckwangt 于 2024-9-7 05:24 编辑
拋磚引玉寫一下有duplicate情況下的backtracking方式 (in python):- from collections import defaultdict
- def minNumberOfFrogs_general(word: str, s: str) -> int:
- n = len(s)
- m = len(word)
-
- if n % m: # s長度要能整除word
- return -1
- result = -1
-
- # curr_comb = a list of length, 代表了目前組合成的每組字的長度, curr_comb[i] range: [1, m]
- def backtrack(curr_comb, index, word_map):
- nonlocal result
- if index == n and len(curr_comb) == n // m:
- result = n // m
- return
- curr_c = s[index]
- possible_positions = word_map[curr_c]
- for next_index in possible_positions:
- if next_index == 0: # 可以開始一個新的word
- curr_comb.append(1)
- backtrack(curr_comb, index + 1, word_map)
- curr_comb.pop()
- continue
- for i, curr_len in enumerate(curr_comb):
- if next_index == curr_len:
- curr_comb[i] += 1
- backtrack(curr_comb, index + 1, word_map)
- curr_comb[i] -= 1
- return
-
- word_map = defaultdict(list)
- for i, c in enumerate(word):
- word_map[c].append(i)
- backtrack([], 0, word_map)
- print(f"{result=}")
复制代码 test cases:- minNumberOfFrogs_general("croak", "croak")
- minNumberOfFrogs_general("croak", "croakcroak")
- minNumberOfFrogs_general("croak", "crcoakroak")
- minNumberOfFrogs_general("croak", "croakcrook")
- minNumberOfFrogs_general("crook", "crookcrook")
- minNumberOfFrogs_general("cook", "cocokook")
- minNumberOfFrogs_general("ook", "ooookk")
- minNumberOfFrogs_general("ook", "okoook")
- minNumberOfFrogs_general("ook", "oookokook")
复制代码 output:- result=1
- result=2
- result=2
- result=-1
- result=2
- result=2
- result=2
- result=-1
- result=3
复制代码 |
|