leetcode 126. Word Ladder II (双向BFS + DFS)

算法提高之搜索:BFS中的双向广搜和A-star 目录1、双向广搜1.1、字串变换2、A-star2.1、第k短路2.2、八数码 1、双向广搜 1.1、字串变换 #include <iostream> #include <cstring> #include <algorithm> #include <queue> #include <unordered_map> using namespace std; //规则数 最多是6 const int N = 6; //记录有多少个规则 int n 阅读详情

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:

Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:

Input:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]

Output:
[
[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”]
]
Example 2:

Input:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”]

Output: []

Explanation: The endWord “cog” is not in wordList, therefore no possible transformation.

127题的升级版,127题只要求输出最短路径是多长,而本题让输出所有的最短路径

思路:
还是127题的双向BFS思路,但是因为要输出所有的路径,中间不能在wordList中把单词删除,因为可能多个路径用到同一个单词

而且一个单词可以改变不同的位变成多个单词,因此需要一个parent和children的关系,
利用这个parent和children的关系, 用DFS即可找到所有的路径

同时注意因为是双向的,如果方向是反向的,parent会变成child,而child是parent

思路是参照某大神的方法
因为很复杂,具体思路写在代码注释里面

//18ms, faster than 94.15% (current time)..
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        HashSet<String> dict = new HashSet<String>(wordList);
        List<List<String>> result = new ArrayList<List<String>>();
        
        //each transformed word must exist in word list, beginWord is not a transformed word..
        if (!dict.contains(endWord)) {
            return result;
        }
        
        boolean found = false;
        boolean backward = false;  //true when from q2 to q1..
        int len = beginWord.length();
        
        //save parent word and their children..
        HashMap<String, List<String>> children = new HashMap<>();
        
        //bidirection BFS, begin and end queue..
        HashSet<String> q1 = new HashSet<String>() {{add(beginWord);}};
        HashSet<String> q2 = new HashSet<String>() {{add(endWord);}};
        
        while (!q1.isEmpty() && !q2.isEmpty() && !found) {
            
            if (q1.size() > q2.size()) {
                //swap q1 and q2..
                HashSet<String> tmp = q2;
                q2 = q1;
                q1 = tmp;
                
                //if swap, then direction be opposite..
                backward = !backward;
            }
            
            //remove word in q1, q2 from dict to prevent duplicated words..
            for (String word : q1) {
                dict.remove(word);
            }
            
            for (String word : q2) {
                dict.remove(word);
            }
            
            HashSet<String> queue = new HashSet<>(); //BFS next level..
            
            //this for part is a level in BFS..
            for (String word : q1) {
                //cannot change String word, change to char array..
                char[] cWord = word.toCharArray();
                
                for (int i = 0; i < len; i++) {
                    char before = cWord[i];  //save char before change..
                    
                    //try every char from 'a' to 'z'..
                    for (char c = 'a'; c <= 'z'; c++) {
                        cWord[i] = c;
                        //cannot put this parent outside for loop..
                        //because when backward, parent has changed..
                        String parent = word;
                        String child = String.valueOf(cWord);  //char array to String..
                        
                        if (q2.contains(child)) {  //found the destination..
                            found = true;
                            
                            //add parent child pair..
                            //but if backward is true, parent and child are opposite..
                            if (backward) {
                                String tmp = parent;
                                parent = child;
                                child = tmp;
                            }
                            if (children.get(parent) == null) {
                                List<String> tmpChildren = new ArrayList<>();
                                tmpChildren.add(child);
                                children.put(parent, tmpChildren);
                            } else {
                                children.get(parent).add(child);
                            }
                            
                       //if already found, means founded in previous level(shorter path)..
                       //so this path is not necessary..
                        } else if (dict.contains(child) && !found) {
                            //add this child word to queue for next level BFS..
                            queue.add(child);
                            
                            //add parent, child pair to children..
                            //but if backward is true, they are opposite..
                            if (backward) {
                                String tmp = parent;
                                parent = child;
                                child = tmp;
                            }
                            if (children.get(parent) == null) {
                                List<String> tmpChildren = new ArrayList<>();
                                tmpChildren.add(child);
                                children.put(parent, tmpChildren);
                            } else {
                                children.get(parent).add(child);
                            }
                        }
                    }
                    //after try every bit, revert it..
                    cWord[i] = before;
                }
            }
            
            q1 = queue;
        }
        
        if (found) {
            List<String> path = new ArrayList<String>() {{add(beginWord);}}; //every path in result..
            getPath(beginWord, endWord, path, children, result);
        }
        
        return result;
    }
    
    //use DFS to find all the path from parent, child pair..
    public void getPath(String beginWord, String endWord, List<String> path,
                       HashMap<String, List<String>> children, List<List<String>> result) {
        if (beginWord.equals(endWord)) {
            //create new list of path, cannot add path reference directly..
            List<String> tmpPath = new ArrayList<String>(path);
            result.add(tmpPath);
            return;
        }
        
        //some path stopped because is not the shortest, so have no child..
        if (!children.containsKey(beginWord)) {
            return;
        }
        
        //DFS..
        for (String word : children.get(beginWord)) {
            path.add(word);
            getPath(word, endWord, path, children, result);
            path.remove(word);
        }
    }
QT绘制饼图+柱状图+折线图 使用qt绘制,折线图,饼图,柱状图,多柱状图 阅读详情

相关推荐

光电振荡器(OEO):从原理到应用,解锁高频微波信号新纪元

本文深入解析了光电振荡器(OEO)的核心原理与前沿应用。OEO通过巧妙的光-电-光转换机制,利用光学谐振腔产生高频、高纯度、低相位噪声的微波信号,有效突破了传统电子电路的频率瓶颈。文章详细拆解了其工作流程,并探讨了在雷达系统、高速光通信及精密测量等领域的硬核应用价值。

weixin_29231027的博客 364

LeetCode_Array_126. Word Ladder II单词接龙II(C++)【双向BFS构图+DFS寻找路径】

1,题目描述 英文描述 Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the wo...

&再见萤火虫&的博客 749

Boost变换电路在新能源车充电系统中的创新应用与挑战

本文探讨了Boost变换电路在新能源车充电系统中的创新应用与挑战,重点分析了其在高压快充、能量回收等场景中的技术突破。通过电力电子仿真和新型器件应用,如SiC MOSFET,显著提升了功率密度和转换效率。同时,文章还深入讨论了电磁兼容性(EMC)挑战及智能控制算法的实际应用,为新能源车充电系统的优化提供了实用解决方案。

7z8x2c4v6b9的博客 217

LeetCode430. 扁平化多级双向链表

LeetCode430. 扁平化多级双向链表 1. 问题描述 2. 思路 3. 代码 /** * Definition for a Node. * type Node struct { * Val int * Prev *Node * Next *Node * Child *Node * } */ func flatten(root *Node) *Node { dfs(root) return root } func dfs(nod

菜到不敢run 562

SAP资产按每天折旧功能介绍

注意:此处在计算百分比时将30天作为剩余使用寿命,因为SAPS/4HANA中的计算是通过考虑购置第一年的折旧总天数来进行的。这是因为我在计算总使用寿命时只使用了365天,如果剩余使用寿命大于1年,SAPS/4HANA会将闰年规范化为365天。此功能仅对确定使用寿命或剩余寿命百分比的折旧键有用,如果需要,这种折旧到日的解决方案可以应用于需要每天计算折旧的跨行业(任何国家/行业)。注意:这里在计算百分比时考虑了2天,因为364天已经过期,但目前我们到达2024年,使用寿命为366天。它只会在下一年生效。

yanzibing99的博客 1560

[机器学习-回归实例] 李宏毅机器学习作业一:PM2.5 预测实例

[机器学习-回归实例] 李宏毅机器学习作业一:PM2.5 预测实例 简介   这是一个回归预测的实例,数据集来自李宏毅的《机器学习》课程的第一次作业,可以用来训练一个线性回归模型或者其他的回归模型,动手实践学习到的理论知识,在实践中去发现问题。这篇文章主要包括数据集的解释、数据的预处理过程及线性回归模型的代码实现这三个部分。由于这个数据集并不能直接使用,还需进行一些重构,为了对初学者更友好一些,我会提供重构完的可以读取后就直接使用的数据集,我也会提供 Matlab\rm MatlabMatlab 可直接使用

qq_27309515的博客 3574

LeetCode---126双周赛

LeetCode---126双周赛---模拟+二维背包

V_zjs的博客 975

用AI从0开始量化交易-制定学习计划安装学习环境

量化小白,利用AI从零开始学量化

weixin_52285994的博客 2112

LeetCode Word Ladder II(双向广搜)

Word Ladder II,双向广搜

丿Smilē 丶晨星灬 810

Cesium圆形波纹/雷达扩散效果扩展类CircleWaveMaterialProperty

本文是基于原创内容进行部分修改,原文出处:https://blog.csdn.net/chudage11/article/details/101632482 SuperMapCesium支持该类似扩展类,以下是原生Cesium调用扩展类CircleWaveMaterialProperty说明 1.扩展类CircleWaveMaterialProperty.js import*asCesiumfrom'cesium' varCircleWaveMaterial={ Circl...

一碗老面的博客 2998

13、数据来源介绍与操作指南

本文详细介绍了多种数据源的特点、操作步骤及适用场景,包括元数据数据源、MongoDB数据源、Pentaho Data Integration数据源、OLAP数据源、Pentaho分析数据源和OLAP4J数据源。通过流程图和表格对比,帮助用户理解不同数据源的选择与使用方法,并提供了实际应用案例和注意事项,旨在提升数据获取与分析效率,支持高效报告生成。

ik678901234的博客 148

leetcode 126 Word Ladder II

题目连接 https://leetcode.com/problems/word-ladder-ii/ Word Ladder II Description Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequenc...

dong12276的博客 314

足式机器人全身 MPPI: 利用 MPPI 对足式机器人进行实时全身控制

本研究首次在真实四足机器人上成功部署了基于全身采样的模型预测控制(MPC)系统。采用模型预测路径积分(MPPI)算法,通过并行采样和评估控制轨迹实现实时运动规划。该系统能处理复杂接触场景,完成推箱子、爬越障碍及崎岖地形行走等任务。实验使用Unitree Go1机器人,结合MuJoCo仿真器快速生成运动策略,仅需简单控制策略即可实现稳健操作。硬件验证表明,该方法能有效完成目标导向的箱子推动任务。该成果标志着采样MPC在足式机器人实际应用中的重要突破。

2506_90492529的博客 999

【leetcode】【hard】126. Word Ladder II​​​​​​​

126. Word Ladder II Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWordtoendWord, such that: Only one letter can be c...

lemonade13的博客 174

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

No.231 - LeetCode[126] Word Ladder II - 单词表所有路径 - 经典双向bfs

T掉的代码: /* * @lc app=leetcode id=126 lang=cpp * * [126] Word Ladder II */ // @lc code=start class Solution { public: vector<vector<string>> findLadders(string beginWord,string endWord,vector<string>& wordList) { wo

ShellDawn的博客 248

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode:126Word Ladder II

problem LeetCode 126 Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in th

erzhushashade的博客 227

126. Word Ladder II

题目链接:https://leetcode.com/problems/word-ladder-ii/ 思路,单向BFS,然后dfs。 借用大佬的一张图来直观看一下: 接下来就是有关去重的问题了,为了避免重复产生临近字符串。我们用一个set来保存 当前层使用过的字符串,不能像前一题127单向那样直接在循环里面移除 str, 而是在这一层结束之后,才移除,不然会丢失路径. AC 9...

God_Mood的博客 250

leetcode - 126. Word Ladder II

图的BFS + 树的DFS的题目,最优解应该用双向BFS,以后有机会再来写吧。 class Solution { public: void visit(string beginWord, vector<string> & path, unordered_map<string, unordered_set<string>> & mp, s...

weixin_41938758的博客 167

LeetCode - 解题笔记 - 126 - Word Ladder II

Solution 1 本体要求最小路径,因此BFS没跑,但是要求递归所有最小结果,可能还是需要DFS的,但是当前版本的实现不需要DFS。利用前几个题的分层BFS,以路径为节点可以完成搜索。使用哈希表来优化存在判定的时间。 此外,一个题解中使用了双向BFS来优化搜索空间,整个思路就是交替地从两个单词展开并找到相遇的时刻,此时刻下相遇位置各自搜索路径的结合即为最优方案:详细通俗的思路分析,多解法 - 单词接龙 II - 力扣(LeetCode) (leetcode-cn.com) 我的实现慢的有点过分,但是目前

支锦铭的博客 398

LeetCode 126 Word Ladder II

题目 LeetCode 126 题解: 具体的思路是,分别从起始和结束字符串出发两遍BFS, 得到每个点到起始字符串的最短距离和终点字符串的最短距离。 然后再从起始字符串出发,DFS 寻找路径。由于已经通过BFS得到每个点到两端的最短距离,所以DFS寻找路径可以很大程度的剪枝,从而防止了超时。 AC 代码(c++): struct Node { string word; int d...

weixin_30352191的博客 272

leetcode_c++:Word Ladder II(126)

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:Only one letter can be changed at a time Each i

LandscapeMi 503

leetcode 127. Word Ladder BFS广度优先遍历

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a ti...

JackZhangNJU的专栏 817

LeetCode 1755. 最接近目标值的子序列和(爆搜爆搜,双向dfs)

1755. 最接近目标值的子序列和 给你一个整数数组 nums 和一个目标值 goal 。 你需要从 nums 中选出一个子序列,使子序列元素总和最接近 goal 。也就是说,如果子序列元素和为 sum ,你需要 最小化绝对差 abs(sum - goal) 。 返回 abs(sum - goal) 可能的 最小值 。 注意,数组的子序列是通过移除原始数组中的某些元素(可能全部或无)而形成的数组。 示例 1: 输入:nums = [5,-7,3,5], goal = 6 输出:0 解释:选择整个数组作为选

qq_45260619的博客 660

Leetcode127 双向BFS

今天常规刷题,刷到一道搜索的题目,第一次用单向BFS过了,然后发现耗时是大佬们的10倍,看了下网上的题解,大概学习了一下双向BFS。 双向BFS的特点是,从起点和终点同时出发,交替搜索,如果在中间相遇了,意味着终点和起点之间存在路径。双向BFS一般情况下可以大大减少搜索范围(脑补一下正方形从左上和右下启动,均按圆弧状往外搜索,一旦两个圆弧相交,搜索结束,那么左下角和右上角有大量区域不需要搜索)。...

ZouCharming的专栏 927

BFS 解决 Word Ladder 问题

资源来源于 LeetCode127——Word Ladder。题目描述如下: 以题目给出的例子为例,其实就是在所有路径的权重都为1的情况下求出下列无向图中从节点 hit 到节点 cog 的最短路径: Postscript:图中相互之间只相差一个字母的单词都是相邻节点。这个就是图论算法中的单源最短路,求单源最短路比较通用的算法是 BFS 和 Dijkstra 算法,其区别是 BFS 不能用于带

黄飞的博客专栏 1185
上一篇: leetcode127.Word Ladder (单双向BFS)
下一篇: 待解决:java generics collection initialization
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值