深度优先搜索算法DFS的另外两个例子
继使用dfs解决数独问题之后,这里又遇到两个使用dfs的例子。这里对用的较多的迭代方式dfs的特点和注意事项再次思考:
- 需要将多种排列组合一一列举的问题,可以使用dfs
- 这一类问题可以画出树的形式,有时候是二叉树,有时候可以有很多分叉,比如数独问题的每个节点就有九个分叉
- 一定是深入到叶节点的时候,才是得到了一种组合的情况;不能在半路上,也就是还没深入到最底层的时候就出结果。例如下面代码中113中的Line49,和784中的Line25,包括《使用dfs解决数独问题之后》程序中的Line20,都是深入到叶节点之后再出结果。
113. Path Sum II
该问题可以看出如下的图:
#include<iostream>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 由二维数组生成二叉树
struct TreeNode *createTreeFromArray(int *nums, int numsSize) {
const int numMeansNull = 0;
struct TreeNode *nodes = (struct TreeNode*)calloc(numsSize, sizeof(struct TreeNode));
for (int i = 0; i < numsSize; i++) {
nodes[i].val = nums[i];
int child = i * 2 + 1;
nodes[i].left = (child < numsSize && nums[child] != numMeansNull) ? &nodes[child] : NULL;
child = i * 2 + 2;
nodes[i].right = (child < numsSize && nums[child] != numMeansNull) ? &nodes[child] : NULL;
}
return &nodes[0];
}
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
int currentSum = 0;
int targetSum = 0;
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
targetSum = sum;
dfs(root);
return res;
}
private:
void dfs(TreeNode *t) {
if (t == NULL) {
return;
}
currentSum += t->val;
path.push_back(t->val);
if (currentSum == targetSum && !t->left && !t->right) {
res.push_back(path);
}
else {
dfs(t->left);
dfs(t->right);
}
path.pop_back();
currentSum -= t->val;
}
};
int main() {
//int nums[] = { 5,4,8,11,0,13,4,7,2,0,0,0,0,5,1 };
int nums[] = { 1 };
struct TreeNode* root = createTreeFromArray(nums, 1);
Solution s;
vector<vector<int>> res = s.pathSum(root, 1);
return 0;
}
784.Letter Case Permutation
该问题可以看出如下的图:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
private:
vector<string> res;
vector<int> charIndex;
string inputStr;
public:
vector<string> letterCasePermutation(string S) {
inputStr = S;
// 记录字符串中每个字母的位置
for (int i = 0; i < S.size(); i++) {
if (isChar(S[i])) {
charIndex.push_back(i);
}
}
dfs(0);
return res;
}
public:
void dfs(int index) {
if (index >= charIndex.size()) {
res.push_back(inputStr);
return;
}
chageCapitalLowercase(&inputStr, charIndex[index]);
dfs(index + 1);
chageCapitalLowercase(&inputStr, charIndex[index]);
dfs(index + 1);
}
bool isChar(char c) {
if ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')) {
return true;
}
else {
return false;
}
}
void chageCapitalLowercase(string *s, int index) {
int diff = 'a' - 'A';
if ((*s)[index] > 'Z') {
(*s)[index] -= diff;
}
else {
(*s)[index] += diff;
}
}
};
int main() {
Solution s;
string str("a1b2");
vector<string> res = s.letterCasePermutation(str);
return 0;
}