天天看點

93. Restore IP Addresses

93. Restore IP Addresses

題目

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

           

解析

  • 三重循環,周遊三個小數點的位置,對每個位置check一下即可:【LeetCode】93. Restore IP Addresses](https://www.cnblogs.com/ganganloveu/p/3780607.html)
  • 遞歸,ip位址分4組,檢查每組的合法性。
class Solution_93 {
public:
	bool isValid(string str)
	{
		long temp = atol(str.c_str()); //用int溢出;atol
		if (temp>255)
		{
			return false;
		}
		if (str[0]=='0'&&str.size()>1)
		{
			return false;
		}
		return true;
	}
	void dfs(vector<string> &res, string t, string s, int cnt)
	{
		if (cnt>3)
		{
			return;
		}
		if (cnt==3&&isValid(s)) //最後一組數
		{
			res.push_back(t+s);
			return;
		}
		for (int i = 1; i < 4 && i < s.size();i++)
		{
			string sub = s.substr(0, i);
			if (isValid(sub))
			{
				dfs(res, t + sub + '.', s.substr(i), cnt + 1);
			}
		}
		return;
	}

	vector<string> restoreIpAddresses(string s) {

		vector<string> res;
		string t;
		dfs(res,t,s,0);
		return res;
	}
};
           

題目來源

C/C++基本文法學習

STL

C++ primer