力扣756 金字塔转换(dfs)

题目链接:传送门
力扣的插图

代码:

class Solution {
public:
    unordered_map<string, vector<char>> mp;
    unordered_map<string, int>mp_s;
    char word[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
    string res[10];
    bool solve(int p, int h) {
        
        if(mp_s[res[h]] == -1)return false; 
        if(h > 0 && res[h].size() == res[h - 1].size() - 1) {
            bool rt = 0;
            if(res[h].size() == 1) {
                rt = true;
            }
            else {
                rt = solve(1, h + 1);
            }
            
            if(!rt)mp_s[res[h]] = -1;
            return rt;
        }

        for(int i = p; i < res[h - 1].size(); i++) {
            string tmp = res[h - 1].substr(i - 1, 2);
            for(int j = 0; j < mp[tmp].size(); j++) {
                res[h] += mp[tmp][j];
                if(solve(i + 1, h)) {
                    return true;
                }
                res[h].pop_back();
            }
        }
        return false;
    }

    bool pyramidTransition(string bot, vector<string>& ald) {
        for(int i = 0;i < ald.size(); i++) {
            mp[ald[i].substr(0, 2)].push_back(ald[i][2]);
        }
        res[0] = bot;
        return solve(1, 1);
    }
};

python:


class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        mp = defaultdict(list)
        for t in allowed:
            mp[t[:2]].append(t[2])
        @cache
        def dfs(s):
            p = []
            if len(s) == 1:
                return True
            for i in range(1, len(s)):
                cur = mp[s[i -1:i + 1]]
                if len(cur) == 0:
                    return False
                p.append(cur)
            for ns in product(*p):
                if dfs("".join(ns)):
                    return True
            return False
        return dfs(bottom)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值