LeetCode专题-深度优先搜索

目录

  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).

题目大意:给定一组无重复的单词,要求选出几个单词,组成一个单词square,横着读和纵着读的内容相同。

解题思路:用前缀表达式记录拥有特定前缀的单词,再用深度优先搜索在满足前缀条件的单词中进行搜索。

//(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]
]

题目大意:给定一个数组,要从数组中选几个数,使之和等于一个目标值,数组中每个数都可以被选任意多次。

解题思路:利用深度优先搜索,对数组中的每个数一一“选中”,测试哪一个分支满足条件,保留满足条件的分支。

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);
    }
};

测试一下,

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]
]

题目大意:和上一题基本相同,有差别的在于,数组中的每个元素都只能被选中一次。

解题思路:加一个记录当前数组最近“选中”位置的变量。

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);        
    }
};

测试一下,

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.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容