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)


这种扫描combination的挺多的,一般都是backtracking, 那么要考虑的:

1. 符合条件的解:  对于单个数字, 0-255之间,且 010为无效。 对于整个解,有四个数字构成且无剩余数字

2. 停止条件: 达到1 之后满足

3. 回溯: 这里我定式思维了一下。。。从index+1继续回溯,其实是i+1..., 总之还是push, 回溯, pop来做。。。。


<span style="color:#333333;">class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
    	vector<string> res;
    	vector<string> solution;
    	scanIp(s,0,res,solution);
    	return res;
    }

private:
    bool isValid(const string& s){
    	int n=s.size();
</span><span style="color:#ff0000;">    	if (n==0 || n>3)
    		return false;
    	if (s[0]=='0' && n>1)
    		return false;
    	if (n==3 && atoi(s.c_str())>255)
    		return false;</span><span style="color:#333333;">
    	return true;
    }

    void scanIp(const string& s, int index, vector<string>& res, vector<string>& solution){
    	if (solution.size()==4){ // stopping condition, have 4 numbers
    		</span><span style="color:#ff0000;">if (index==s.size())</span><span style="color:#333333;">{ // there is not left numbers, otherwise, invalid
    			string tmp=solution[0];
    			for (int i=1; i<4; i++)
    				tmp=tmp+"."+solution[i];
    			res.push_back(tmp);
    		}
    		return;
    	}

    	string num;
    	for (int i=index; i<s.size()&& i<index+3; i++){
    		num.push_back(s[i]);
    		if (isValid(num)){
    			solution.push_back(num);
    			scanIp(s,</span><span style="color:#ff0000;">i+1</span><span style="color:#333333;">, res, solution);
    			solution.pop_back();
    		}
    	}
    }
};
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值