DFS solving routine

DFS solving routine

If DFS encounter a problem, the basic code routines as follows:

1, we basically use recursion to solve the problem of DFS, so to determine the conditions for ending recursive, that is, the end of the DFS conditions.

2, write DFS function routines framework. As follows

void dfs() {
}

int main() {
    读入数据

    dfs();

    return 0;
}

3, it was confirmed DFS function parameters. This is the most difficult place, needs to be determined based on specific topics. In general, we have to confirm this state according to the search topic.

4, if there is backtracking, need to ensure that each time after the completion of DFS can restore the original state, so the search will not back an error.

For example

Let's take a few examples to explain.

LeetCode 784  capitalization full array

Topic Link to https://leetcode-cn.com/problems/letter-case-permutation/ .

输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]

Accordance with the requirements of the subject, we know that no letter will have two possible paths: Path 1, to lower case letters; path 2, uppercase letters changed. As shown below:

The above examples thus has two letters, is the possibility of 2 * 2 = 4 species.

Search termination condition

Termination condition must be searched for the string length.

Search function parameters

Let's analyze what parameter dfs () function requires. Since the result is a string, so DFS () function,

1, need to pass a string representing the current character is kind of how.

2, but also a position that represents the current enumeration to which local string, which is the first of several strings.

So we can determine this question dfs () function prototype should be as follows:

//参数s:表示当前字符串的内容
//参数index:表示现在枚举到字符串s的第几位
void dfs(string &s, int index) {
    if (index==s.length()) {
        return;
    }
    dfs(s, index+1);//保持不变直接搜索下一位
    if (s[index]>='A') {
        //是字母
        s[index] ^= 32;//大小写切换
        dfs(s, index+1);//搜索下一位
    }
}

Start calling way

dfs(s, 0);//表示从第0位开始搜索字符串s

Backtracking

This problem does not require backtracking, search directly on it.

AC reference code

class Solution {
public:
    vector<string> ans;

    vector<string> letterCasePermutation(string S) {
        dfs(S, 0);
        return ans;
    }

    void dfs(string &s, int idx) {
        if (s.length()==idx) {
            ans.push_back(s);
            return;
        }

        //本位不变,搜索下一位
        dfs(s, idx+1);

        //本位变,搜索下一位
        if (s[idx]>='A') {
            s[idx] ^= 32;
            dfs(s, idx+1);
        }
    }
};

LeetCode 77  combination

Topic Link to https://leetcode-cn.com/problems/combinations/ . Input integers n and k, the number of stars in the composition 1 ~ n k digits.

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Thinking this question is in the numbers 1 ~ n, k selected from small to large numbers, so the answer must be determined.

Search termination condition

Termination condition must be searched digits reaches k.

Search function parameters

1, an array, indicating that you are searching out a few numbers.

2, an integer number representing start to begin the search.

3, a represents an integer number n to terminate the search. This can be represented by the global variable, global variable if this parameter can be omitted.

4, leaving a few numbers need to search left.

Thus, the function prototype to this question dfs () may be expressed as follows:

//参数1:path存放已经搜索出了几个数据
//参数2:start表示从哪个数字开始搜索
//参数3:n表示搜索的最大数据
//参数4:left还剩下几个数没有搜索到
void dfs(vector<int> &path, int start, int n, int left);

Start calling way

//从0开始搜索,搜索到数据n,一共搜索k个数字
dfs(path, 0, n, k);

Backtracking

        path.push_back(i);//将数据i保存到path中
        dfs(path, i+1, n, k-1);
        path.pop_back();//回溯

AC reference code

class Solution {
public:
    vector<vector<int>> ans;//答案

    vector<vector<int>> combine(int n, int k) {
        vector<int> path;

        dfs(path, 1, n, k);

        return ans;
    }

    void dfs(vector<int> &path, int start, int n, int k) {
        if (0==k) {
            //搜索到了
            ans.push_back(path);
            return;
        }

        for (int i=start; i<=n; i++) {
            //加入当前数据
            path.push_back(i);
            dfs(path, i+1, n, k-1);
            path.pop_back();//回溯
        }
    }
};

While these two examples are very simple, but hope that through the analysis of such a simple example, give you a template to establish routines written DFS program.

Published 239 original articles · won praise 291 · Views 1.07 million +

Guess you like

Origin blog.csdn.net/justidle/article/details/104925699
dfs