DFS

1. 二叉树路径总和

LeetCode 113 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> path;
        dfs(path,root,sum);
        return ans;
        
    }
    void dfs(vector<int>& path,TreeNode* root, int sum)
    {
        if(!root) return;
        path.push_back(root->val);
        if(!root->left && !root->right)
        {
            int sum2 = accumulate(path.begin(),path.end(),0);
            if(sum2 == sum)
            {
                ans.push_back(path);
                return;
            }
                
        }
        else
        {
            dfs(path, root->left,sum);
            if(root->left)
                path.pop_back();
            dfs(path, root->right,sum);
            if(root->right)
                path.pop_back();
        }
    }
};

如若不使用引用,则不需要恢复现场

2. 字母大小写全排列

Leetcode 784 给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。

class Solution {
public:
    vector<string> ans;
    vector<string> letterCasePermutation(string S) {
        dfs(S,0);
        return ans;

    }
    void dfs(string s, int i)
    {
        if(i == s.size())
        {
            ans.push_back(s);
            return;
        }
        dfs(s,i+1);
        if(s[i] >= 'A')
        {
            s[i] ^= 32;
            dfs(s,i+1);
        }
    }
};

3. 组合

Leetcode 77 从n个数中选k个

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

    }
};

4. 二叉树所有路径

Leetcode 257 给定一个二叉树,返回所有从根节点到叶子节点的路径。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> ans;
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        dfs(root, path);
        return ans;

    }
    void dfs(TreeNode * root, string path)
    {
        if(!root) return;

        if(path.size()) path += "->";
        path += to_string(root->val);

        if(!root->left && !root->right) ans.push_back(path);
        else
        {
            dfs(root->left,path);
            dfs(root->right,path);
        }
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。