活跃农民
- 积分
- 556
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-4-6
- 最后登录
- 1970-1-1
|
写个树,DFS
- def form_words_from_pairs(pairs, word):
- # pairs.sort(key=cmp_to_key(compare))
- if len(word) > len(pairs):
- return False
- dic = {}
- for c in word:
- dic[c] = dic.get(c, 0) + 1
- return form_words_from_pairs_helper(pairs, dic, len(word))
- def form_words_from_pairs_helper(pairs, dic, count):
- if not pairs:
- return True if count == 0 else False
- first, second = pairs[0][0], pairs[0][1]
- if dic.get(first, 0) != 0 and dic[first] > 0:
- dic[first] -= 1
- result = form_words_from_pairs_helper(pairs[1:], dic, count-1)
- if result:
- return result
- else:
- dic[first] += 1
- if dic.get(second, 0) != 0 and dic[second] > 0:
- dic[second] -= 1
- result = form_words_from_pairs_helper(pairs[1:], dic, count-1)
- if result:
- return result
- else:
- dic[second] += 1
- return True if count == 0 else False
复制代码 |
|