一般涉及到数学中的组合求解的问题一般使用的问题,可以通过修改dfs算法+递归进行相应的求解。
此问题的 解法一般是进行对给出的 字符串进行深度搜索,需要处理各种边界条件,同时需要准确的判定出递归的终止条件。
这类问题一般是大致上相同,主要是处理边界条件的不同。
下面例题为leetcode上一道经典例题。
此问题的边界条件是:
1.ip每一段的大小最多为3
2.ip每一段的大小需要检验其合理性,不能大于255,同时每一段需要有值。
3.一共需要划分4段。
代码:
1 #include <iostream>
2 #include <string>
3 #include <vector>
4 #include <list>
5 using namespace std;
6 //给出一个包含数字的字符串,给出可能的ip组合
7 //应该使用dfs+递归实现
8
9 //用来保存运算的结果
10
11 string changeToString(vector<string>path)
12 {
13 string str = "";
14 auto it1 = path.begin();
15 auto it2 = path.end();
16 while (it1 != it2)
17 {
18 str += (*it1);
19 //添加上“."
20 str += ".";
21 ++it1;
22 }
23 //去除最后的“."
24 int length = str.length();
25 str = str.substr(0, length - 1);
26 return str;
27 }
28
29 bool isAvailable(string out)
30 {
31
32 int length = out.length();
33 if (length == 0)
34 return false;
35 if (length > 1 && out[0] == '0')
36 return false;
37 int num = atoi(out.c_str());
38 if (num <0 || num >= 256)
39 return false;
40 return true;
41 }
42
43 void dfs(vector<string>&result, string s, int pos, vector<string>&path)
44 {
45 if (path.size() == 4)
46 {
47 if (pos != s.length())
48 return;
49 else
50 {
51 //将path转换成string 添加到result中
52 result.push_back(changeToString(path));
53 return;
54 }
55 }
56 else
57 {
58 for (int i = pos; i < s.length() && i < pos + 3; i++)
59 {
60 //开始递归过程
61 string out = s.substr(pos, i-pos+1);
62 if (isAvailable(out))
63 {
64 path.push_back(out);
65 dfs(result, s, i + 1, path);
66 //当处理完之后将vector中最后一个元素pop
67 path.pop_back();
68 }
69
70 }
71 }
72
73 }
74
75 vector<string> restoreIpAddresses(string s)
76 {
77 int length = s.length();
78 //用来保存输出的结果
79 vector<string> result;
80 //判断长度是否符合要求
81 if (length == 0 || length < 4 || length>12)
82 return result;
83
84 //用来保存每一个可能的ip组合
85 vector<string> path;
86 //调用dfs处理函数
87 dfs(result, s, 0, path);
88 return result;
89
90 }
91
92 int main()
93 {
94 string str;
95 vector<string> list;
96 cin >> str;
97 list=restoreIpAddresses(str);
98 auto it1 = list.begin();
99 auto it2 = list.end();
100 while (it1 != it2)
101 {
102 cout << *it1 << endl;
103 ++it1;
104 }
105 return 0;
106 }
运行结果: