为什么说回溯是暴力枚举

因为回溯的本质是循环的嵌套

93. 复原 IP 地址 - 力扣(LeetCode)

在这道题中,如果直接写for循环,那么四重循环也能得到结果:

class Solution {
public:
    vector restoreIpAddresses(string s) {
		vector res;
        if (s.size() < 4)
            return res;
		for (int a = 1; a < 4; a++)  
			for (int b = 1; b < 4; b++)
				for (int c = 1; c < 4; c++) 
                    for (int d = 1; d < 4; d++)  {
                        if (a + b + c + d != s.size())
                            continue;
                        // cout << a << " " << b << " " << c << " " << d <

你可能感兴趣的:(算法,leetcode,算法,职场和发展)