LeetCode專題-深度優(yōu)先搜索

目錄

  1. Word Squares
  2. Combination Sum
  3. Combination Sum II

425. Word Squares

Given a set of words (without duplicates), find all word squares you can build from them.

A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.

b a l l
a r e a
l e a d
l a d y

Note:

There are at least 1 and at most 1000 words.
All words will have the exact same length.
Word length is at least 1 and at most 5.
Each word contains only lowercase English alphabet a-z.
Example 1:

Input:
["area","lead","wall","lady","ball"]

Output:
[
 [ "wall",
   "area",
   "lead",
   "lady"
 ],
 [ "ball",
   "area",
   "lead",
   "lady"
 ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).

題目大意:給定一組無(wú)重復(fù)的單詞贪染,要求選出幾個(gè)單詞肢专,組成一個(gè)單詞square棚饵,橫著讀和縱著讀的內(nèi)容相同蔼囊。

解題思路:用前綴表達(dá)式記錄擁有特定前綴的單詞,再用深度優(yōu)先搜索在滿足前綴條件的單詞中進(jìn)行搜索播玖。

//(DFS, backtrace + Prefix tree)
struct TrieNode {
    TrieNode(){}
    ~TrieNode() {}
    shared_ptr<TrieNode>    next[26];
    vector<string>          words; //words in dict that have the prefix
    // for this node
};
void insertWS(const string &word, shared_ptr<TrieNode> node) {
    for (auto const c : word) {
        int idx = c - 'a'; //get idx of node for c
        if (node->next[idx] == nullptr) {
            //create new trie node
            node->next[idx] = make_shared<TrieNode>();
        }
        // move to prefix tree(trie) node with c
        node = node->next[idx];
        // word is one with prefix contained in node
        node->words.push_back(word);
    }
}
vector<string> findCandidates(shared_ptr<TrieNode> node, const string &prefix) {
    for (auto const & c : prefix) {
        int idx = c - 'a';
        if (node->next[idx] == nullptr) {
            return {};
        }
        node = node->next[idx]; //level-by-level, search the node for input prefix
    }
    return node->words; //return a copy of words with prefix
}
void wordSquaresDFS(shared_ptr<TrieNode> node, const int N, vector<string> &path, vector<vector<string>> &ans) {
    size_t newIdx = path.size();
    if ((int)newIdx == N) {
        //if path is long enough, save into ans
        ans.push_back(path);
        return;
    }

    string prefix;
    //path length must be shorter than word length
    for (auto const & word : path) {
        //get the newIdx-th column
        prefix += word[newIdx];
    }

    //take the newIdx-th colum as the new row, find all candidates
    //  words that contain the row as prefix
    vector<string> candidates = findCandidates(node, prefix);
    for (auto const & candidate : candidates) {
        //choose and un-choose one candidate
        path.push_back(candidate);
        wordSquaresDFS(node, N, path, ans); //advance to next level
        path.pop_back(); //un-choose before return
    }
}
vector<vector<string>> wordSquares(vector<string>& words) {
    vector<vector<string>> ans;
    if (words.size() == 0) {
        return ans;
    }

    // build the trie tree
    const int N = (int)words.at(0).size();
    auto root = make_shared<TrieNode>();
    for (auto const & word : words) {
        insertWS(word, root);
    }

    // DFS
    vector<string> path;
    for (auto const & word : words) {
        path.push_back(word);
        wordSquaresDFS(root, N, path, ans);
        path.pop_back();
    }

    return move(ans);
}

void WordSquares() {
    cout << "WordSquares" << endl;
    auto anss = wordSquares(vector<string>{ "area","lead","wall","lady","ball" });
    for (auto & ans : anss) {
        Print(ans);
    }
}

39. Combination Sum

Medium

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

題目大意:給定一個(gè)數(shù)組肉津,要從數(shù)組中選幾個(gè)數(shù),使之和等于一個(gè)目標(biāo)值迅箩,數(shù)組中每個(gè)數(shù)都可以被選任意多次。

解題思路:利用深度優(yōu)先搜索处铛,對(duì)數(shù)組中的每個(gè)數(shù)一一“選中”饲趋,測(cè)試哪一個(gè)分支滿足條件拐揭,保留滿足條件的分支。

class Solution {
    void combinationSumDFS(const vector<int>& candidates,       vector<int>& path, int target, int start, vector<vector<int>> &ans) {
        if (target < 0) return;
        if (target == 0) {ans.push_back(path); return;}
        for (int i = start; i < candidates.size(); ++i) {
            path.push_back(candidates[i]);
            combinationSumDFS(candidates, path, target - candidates[i], i, ans);
            path.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> ans;
        vector<int> path;
        combinationSumDFS(candidates, path, target, 0, ans);
        return move(ans);
    }
};

測(cè)試一下奕塑,

Success
Details
Runtime: 8 ms, faster than 99.33% of C++ online submissions for Combination Sum.
Memory Usage: 9.5 MB, less than 80.12% of C++ online submissions for Combination Sum.

40. Combination Sum II

Medium

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

題目大意:和上一題基本相同堂污,有差別的在于,數(shù)組中的每個(gè)元素都只能被選中一次龄砰。

解題思路:加一個(gè)記錄當(dāng)前數(shù)組最近“選中”位置的變量盟猖。

class Solution {
    void combinationSumDFS(const vector<int>& candidates, vector<int>& path, int target, int start, vector<vector<int>> &ans) {
        if (target == 0) {
            sort(path.begin(), path.end());
            if (find(ans.begin(), ans.end(), path) == ans.end()) {
                ans.push_back(path);
            }
            return;
        }
        else if (target < 0) {
            return;
        }

        // DFS search range
        for (int i = start; i < (int)candidates.size(); i++) {
            path.push_back(candidates[i]);
            combinationSumDFS(candidates, path, target - candidates[i], i + 1, ans);
            path.pop_back();
        }
    }    
public:
    
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> ans;
        vector<int> path;
        combinationSumDFS(candidates, path, target, 0, ans);
        return move(ans);        
    }
};

測(cè)試一下,

Success
Details
Runtime: 44 ms, faster than 15.78% of C++ online submissions for Combination Sum II.
Memory Usage: 9 MB, less than 81.12% of C++ online submissions for Combination Sum II.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末换棚,一起剝皮案震驚了整個(gè)濱河市扒披,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌圃泡,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,464評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件愿险,死亡現(xiàn)場(chǎng)離奇詭異颇蜡,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)辆亏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,033評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門风秤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人扮叨,你說(shuō)我怎么就攤上這事缤弦。” “怎么了彻磁?”我有些...
    開封第一講書人閱讀 169,078評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵碍沐,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我衷蜓,道長(zhǎng)累提,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,979評(píng)論 1 299
  • 正文 為了忘掉前任磁浇,我火速辦了婚禮斋陪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘置吓。我一直安慰自己无虚,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,001評(píng)論 6 398
  • 文/花漫 我一把揭開白布衍锚。 她就那樣靜靜地躺著友题,像睡著了一般。 火紅的嫁衣襯著肌膚如雪构拳。 梳的紋絲不亂的頭發(fā)上咆爽,一...
    開封第一講書人閱讀 52,584評(píng)論 1 312
  • 那天梁棠,我揣著相機(jī)與錄音,去河邊找鬼斗埂。 笑死符糊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的呛凶。 我是一名探鬼主播男娄,決...
    沈念sama閱讀 41,085評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼漾稀!你這毒婦竟也來(lái)了模闲?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,023評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤崭捍,失蹤者是張志新(化名)和其女友劉穎尸折,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體殷蛇,經(jīng)...
    沈念sama閱讀 46,555評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡实夹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,626評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了粒梦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片亮航。...
    茶點(diǎn)故事閱讀 40,769評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖匀们,靈堂內(nèi)的尸體忽然破棺而出缴淋,到底是詐尸還是另有隱情,我是刑警寧澤泄朴,帶...
    沈念sama閱讀 36,439評(píng)論 5 351
  • 正文 年R本政府宣布重抖,位于F島的核電站,受9級(jí)特大地震影響叼旋,放射性物質(zhì)發(fā)生泄漏仇哆。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,115評(píng)論 3 335
  • 文/蒙蒙 一夫植、第九天 我趴在偏房一處隱蔽的房頂上張望讹剔。 院中可真熱鬧,春花似錦详民、人聲如沸延欠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,601評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)由捎。三九已至,卻和暖如春饿凛,著一層夾襖步出監(jiān)牢的瞬間狞玛,已是汗流浹背软驰。 一陣腳步聲響...
    開封第一講書人閱讀 33,702評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留心肪,地道東北人锭亏。 一個(gè)月前我還...
    沈念sama閱讀 49,191評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像硬鞍,于是被迫代替她去往敵國(guó)和親慧瘤。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,781評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,347評(píng)論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,585評(píng)論 0 23
  • 2019年1月23日晚上6:30的讀書會(huì)我本來(lái)是找了個(gè)好理由不想來(lái)的固该,因?yàn)槲腋忻傲?還因?yàn)樽x書會(huì)上是要發(fā)言...
    五月花海閱讀 249評(píng)論 0 1
  • 二胎寶媽的實(shí)話實(shí)說(shuō)伐坏,既溫馨又狼狽不堪 老公和我都是獨(dú)生子女怔匣,深感一個(gè)人的孤獨(dú)寂寞,所以我們一直都是打算要老二桦沉。但是...
    慈滿天下閱讀 554評(píng)論 1 0
  • 這幾天跟外界幾乎是沒(méi)什么聯(lián)系了吧劫狠。 一個(gè)人獨(dú)處。oh永部!yeah!此處應(yīng)該有激情四射的音樂(lè)呐矾! 整棟房子只有你自己苔埋,可...
    怎料世事閱讀 315評(píng)論 8 0