posted in OJ题解 

题目

https://oj.leetcode.com/submissions/detail/10496925/

分析

树的层次遍历, 唯一的难点在于如何判断两个结点是否在同一层上。

可以除了nodeQue之外,再增加一个depQue, 来记录每个结点的深度。

代码:

class Solution
{
public:
	vector<vector<int>> levelOrder(TreeNode *root)
	{
		queue<TreeNode*> nodeQue;
		queue<int> depQue;
		TreeNode *node;
		int dep;
		int depBefore;
		vector<vector<int>> res;
		vector<int> solution;

		if (!root)
			return res;

		nodeQue.push(root);
		depQue.push(1);
		depBefore = 1;
		while (!nodeQue.empty())
		{
			node = nodeQue.front();
			nodeQue.pop();
			dep = depQue.front();
			depQue.pop();

			if (dep == depBefore)
				solution.push_back(node->val);
			else
			{
				res.push_back(solution);
				depBefore = dep;
				solution.clear();
				solution.push_back(node->val);
			}

			if (node->left)
			{
				nodeQue.push(node->left);
				depQue.push(dep + 1);
			}
			if (node->right)
			{
				nodeQue.push(node->right);
				depQue.push(dep + 1);
			}
		}
		res.push_back(solution);
		return res;
	}
};

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38927101

posted in OJ题解 

题目

https://oj.leetcode.com/problems/decode-ways/

分析

  1. Leetcode: Climbing Stairs这道题类似, 都是用类似斐波那契数列的算法解决问题。只不过在递归或者迭代时加一点条件判断。

  2. 运用动态规划思想, 先想出递归的算法, 然后再改变成迭代的方式提高算法效率。

  3.  递归的算法:

      设前n个数的decode ways是f(n), 则

            若最后俩数小于26, 则

                  f(n) = f(n-1) + f(n-2);

            否则

                  f(n) = f(n-1);

  1. 再改造成迭代的算法:

      设前n个数的decode ways是s(n), 则

            若最后俩数小于26, 则

                  s(n) = s(n-1) + s(n-2);

            否则

                  s(n) = s(n-1);

  1. 因为“0”是一个比较特殊的数字, 所以针对一些测试用例, 需要对算法进行一些改进。 

这些改进如果没有测试用例, 感觉很难就作出来。 这大概也是测试工程师的作用吧。

代码

class Solution
{
public:
	int numDecodings(string s)
	{
		if (s.empty())
			return 0;
		if (s[0] == '0')
			return 0;
		if (s.size() == 1)
			return 1;

		int a, b, c;
		a = 1;
		b = 1; 
		for (int i = 1; i < s.size(); i++)
		{
			if (s[i] == '0' && s[i-1] == '0')
				return 0;
			if (s[i] == '0' && s[i-1] > '2')
				return 0;

			if (stoi(s.substr(i-1, 2)) > 26)
				c = b;
			else if (s[i] == '0')
				c = a;
			else if (s[i-1] == '0')
				c = b;
			else
				c = a + b;

			a = b;
			b = c;
		}

		return c;
	}
};

参考

http://blog.csdn.net/worldwindjp/article/details/19938131

http://fisherlei.blogspot.com/2013/01/leetcode-decode-ways-solution.html

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38902215

posted in OJ题解 

题目:

https://oj.leetcode.com/problems/word-ladder/

分析:

  1. 求最短路径, 用BFS算法。 [3]

  2. 求各个单词之间的邻接关系, 不能用邻接矩阵, 否则会Time Limit Exceeded。 [2]

因为并非所有单词之间的邻接关系在求解过程中都需要, 只需要求解用到的一些单词的邻居即可。要是求邻接矩阵的话, 会花费大量时间。

  1. 一个单词访问过了之后, 直接从dict中删除即可, 从而避免重复加入队列,进而导致浪费时间。[1]

  2. 关于如何记录路径长, 可以再创建一个depth队列, 这样que队列push时, depth队列也同时的push一个对应的路径。[1]

代码:

class Solution
{
public:
	int ladderLength(string start, string end, unordered_set<string> &dict)
	{
		dict.insert(end);
		queue<string> que;
		queue<int> depth;
		que.push(start);
		depth.push(2);
		int len;

		while (!que.empty())
		{
			string ver = que.front();
			que.pop();
			len = depth.front();
			depth.pop();

			vector<string> res;
			adjacency(ver, dict, res);
			for (auto &r : res)
			{
				if (r == end)
					return len;
				else
				{
					dict.erase(r);
					que.push(r);
					depth.push(len+1);
				}
			}
		}

		return 0;
	};

	void adjacency(const string &ver, const unordered_set<string> &dict, vector<string> &res)
	{
		for (int i = 0; i < ver.size(); i++)
		{
			string temp = ver;
			for (int j = 'a'; j <= 'z'; j++)
			{
				temp[i] = j;
				if (temp != ver && dict.find(temp) != dict.end())
					res.push_back(temp);
			}
		}

		return;
	}
};

参考:

[1] http://blog.csdn.net/lanxu_yy/article/details/17588317

[2] http://blog.csdn.net/yutianzuijin/article/details/12887747

[3] 《数据结构(C++语言版)》(第三版) 邓俊辉  p169

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38867667

posted in OJ题解 

题目

https://oj.leetcode.com/problems/word-search/

分析

  1. 通过递归来实现的DFS搜索。

  2. 需要注意的一点是, 要用一个visited二维vector来记录已经访问的元素, 以后不能再访问了。

  3. visited形参要声明成引用形式, 每次递归后手动的恢复现场。 如果声明成变量的形式, 会超时。

代码

class Solution
{
public:
	bool exist(vector<vector<char>> &board, string word)
	{
		vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
		for (int i = 0; i < board.size(); i++)
		{
			for (int j = 0; j < board[0].size(); j++)
			{
				if (board[i][j] == word[0])
					if (search(board, i, j, word, 0, visited))
						return true;
			}
		}
		return false;
	}

	bool search(vector<vector<char>> &board, int i, int j, string word, int index, vector<vector<bool>> &visited)
	{
		if (index == word.size())
			return true;
		else if (i < 0 || i == board.size() || j < 0 || j == board[0].size())
			return false;
		else if (visited[i][j] == true)
			return false;
		else if (board[i][j] != word[index])
			return false;
		else
		{
			visited[i][j] = true;
			if (search(board, i-1, j, word, index+1, visited)) return true;
			if (search(board, i+1, j, word, index+1, visited)) return true;
			if (search(board, i, j-1, word, index+1, visited)) return true;
			if (search(board, i, j+1, word, index+1, visited)) return true;
			visited[i][j] = false;
		}

		return false;
	}
};

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38826685

posted in OJ题解 

前言:

做到Anagrams这道题, 费了半天劲没明白输入输出要求到底是怎样的。 最后找了两个测试用例终于明白题目要求了。

Input:  ["tea","and","ate","eat","den"]

Output:     ["tea","ate","eat"]

Input:       ["cat","rye","aye","dog", "god","cud","cat","old","fop","bra"]

Output:    ["cat","cat","dog","god"]

题目:

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

https://oj.leetcode.com/problems/anagrams/

分析:

Anagram可以知道Anagram什么意思, 

要点有两个:

        1. 把每个字符串排序后再处理, 可以判断是否是anagram

        2. 把处理好的数据放到map中, 供下次查询

        3. 注意anagram可能会出现三个一组的

代码:

class Solution
{
public:
    vector<string> anagrams(vector<string> &strs)
    {   
        vector<string> res;
        map<string, int> anagram;

        for (int i = 0; i < strs.size(); i++)
        {
            string s = strs[i];

            sort(s.begin(), s.end());
            if (anagram.find(s) == anagram.end())
                anagram[s] = i;
            else
            {
                //如果是第二个anagram
                if (anagram[s] > -1) 
                {
                    res.push_back(strs[anagram[s]]);
                    anagram[s] = -1; 
                }
                res.push_back(strs[i]);
            }
        }

        return res;
    }   
};

参考:

https://oj.leetcode.com/discuss/215/does-return-groups-return-result-vector-string-return-groups

http://www.cnblogs.com/AnnieKim/archive/2013/04/25/3041982.html

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38756403

posted in OJ题解 

题目:

https://oj.leetcode.com/problems/generate-parentheses/

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

分析:

看到题目的之后, 首先在心里模拟生成结果的过程, 比如说n=2时, 首先 生成一个"(", 然后就有两个选择了, 生成"("或")", 再下一步又面临着两个选择。。。以此类推, 每次都有两个选择, 仿佛生成了一棵二叉树。 

Center

这种情况下, 多半要用递归来解决了。递归算法, 最重要的是两点, 一个是找到它终止的边界条件, 一个是找到它每次递归的规律。

首先是终止条件, 显然这个问题的终止条件是, “(”和")"的数量都达到n时,以及")"的数量增长到和"("的数量相等时, 算法就终止了。它的递归规律是, 每次"("的数量或者")"的数量加1。 然后就可以写代码了。

代码:

class Solution
{
public:
    vector<string> generateParenthesis(int n)
    {
		generate(n, 0, 0, "");

		return res;
    }

	void generate(int n, int left, int right, string s)
	{
		if (right == n)
			res.push_back(s);

		if (left < n)
			generate(n, left + 1, right, s + '(');

		if (right < left)
			generate(n, left, right + 1, s + ')');
	}

private:
	vector<string> res;
};

参考:

http://blog.csdn.net/yutianzuijin/article/details/13161721

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38642115

posted in OJ题解 

前言

Leetcode做到Valid Number这道题, 看到 Leetcode题目分类 中说这道题难度为二级(总共五级), 还以为这道题真的很简单。。。真是坑了大爹了。

仔细总结了下, 这道题大概有三种解法:

题目

https://oj.leetcode.com/problems/valid-number/

Validate if a given string is numeric.

Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. 

You should gather all requirements up front before implementing one.

解法一:

这种方法用正则表达式来解决, 算是最简单优雅的一种方法了。

class Solution2
{
public:
    bool isNumber(const char *s) 
    {   
<span style="white-space:pre">	</span>regex re("( *)[+-]?(\\d+|\\d+\\.\\d*|\\d*\\.\\d+)([eE][+-]?\\d+)?");

        if (regex_match(s, re))
            return true;
        else
            return false;
    }   

};

不过截止到发文章, g++ 4.8.2貌似还是没有完全支持正则表达式, 所以这段代码编译会报错。

但是如果用Java或Python的话, 应该没问题了。

另一方面, 面试的时候恐怕不会允许简简单单的用正则表达式来解决这个问题, 所以还要掌握其他方法。

解法二:

2.1 DFA

第二种方法用DFA来解决这个问题, 用到了了编译原理中的tokenizer那部分的思想。

这种方法写代码之前要先画出图来才行,我画的如下:

SouthEast

画的有点乱, 不过领会精神就好。 :)

代码如下:

class Solution2_1
{
public:
public:
	bool isNumber(const char *s)
	{
		int state = 0;

		while (1)
		{
			switch (state)
			{
				case 0:
					if (*s == ' ')
						state = 0;
					else if (*s == '+' || *s == '-')
						state = 1;
					else if (isdigit(*s))
						state = 2;
					else if (*s == '.')
						state = 9;
					else 
						state = 8;
					break;

				case 1:
					if (isdigit(*s))
						state = 2;
					else if (*s == '.')
						state = 9;
					else
						state = 8;
					break;

				case 2:
					if (isdigit(*s))
						state = 2;
					else if (*s == '.')
						state = 3;
					else if (*s == '\0')
						state = 7;
					else if (*s == ' ')
						state = 10;
					else if (*s == 'e' || *s == 'E')
						state = 5;
					else
						state = 8;
					break;
					
				case 3:
					if (isdigit(*s))
						state = 4;
					else if (*s == '\0')
						state = 7;
					else if (*s == ' ')
						state = 10;
					else if (*s == 'e' || *s == 'E')
						state = 5;
					else
						state = 8;
					break;

				case 4:
					if (isdigit(*s))
						state = 4;
					else if (*s == 'e' || *s == 'E')
						state = 5;
					else if (*s == '\0')
						state = 7;
					else if (*s == ' ')
						state = 10;
					else
						state = 8;
					break;

				case 5:
					if (isdigit(*s))
						state = 6;
					else if (*s == '+' || *s == '-')
						state = 11;
					else
						state = 8;
					break;

				case 6:
					if (isdigit(*s))
						state = 6;
					else if (*s == ' ')
						state = 6;
					else if (*s == '\0')
						state = 7;
					else if (*s == ' ')
						state = 10;
					else
						state = 8;
					break;

				case 7:
					return true;

				case 8:
					return false;

				case 9:
					if (isdigit(*s))
						state = 4;
					else
						state = 8;
					break;

				case 10:
					if (*s == '\0')
						state = 7;
					else if (*s == ' ')
						state = 10;
					else
						state = 8;
					break;
				case 11:
					if (isdigit(*s))
						state = 6;
					else 
						state = 8;
					break;
			}
			s++;
		}
	}
};

这段代码可能开起来有点长, 不过只要弄明白了那张状态转换图很容易明白的。

2.2 DFA改进版

上面这段代码可能有点长, 所以用二维数组对其进行改进:

SouthEast 1

代码如下:

class Solution2_2
{
public:
	bool isNumber(const char *s)
	{
		int state = 0;
		int translate[][7] =
		{
			0, 1, 2, 8, 9, 8, 8,	//0
			8, 8, 2, 8, 9, 8, 8,	//1
			10, 8, 2, 5, 3, 7, 8,	//2
			10, 8, 4, 5, 8, 7, 8,	//3
			10, 8, 4, 5, 8, 7, 8, 	//4
			8, 11, 6, 8, 8, 8, 8,	//5
			10, 8, 6, 8, 8, 7, 8,	//6
			7, 7, 7, 7, 7, 7, 7,	//7
			8, 8, 8, 8, 8, 8, 8,	//8
			8, 8, 4, 8, 8, 8, 8,	//9
			10, 8, 8, 8, 8, 7, 8, 	//10
			8, 8, 6, 8, 8, 8, 8		//11
		};

		int type;
		while (1)
		{
			if (*s == ' ')
				type = 0;
			else if (*s == '+' || *s == '-')
				type = 1;
			else if (isdigit(*s))
				type = 2;
			else if (*s == 'e' || *s == 'E')
				type = 3;
			else if (*s == '.')
				type = 4;
			else if (*s == '\0')
				type = 5;
			else 
				type = 6;

			state = translate[state][type];

			if (state == 7)
				return true;
			else if (state == 8)
				return false;

			s++;
		}
	}
};

解法三:

用多个flag来标识现在的状态, 可读性比较差, 不推荐。

class Solution3 {
public:
    bool isNumber(const char *s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if (s == NULL)
             return false;
             
         while(isspace(*s))
             s++;
             
         if (*s == '+' || *s == '-')
             s++;
             
         bool eAppear = false;
         bool dotAppear = false;
         bool firstPart = false;
         bool secondPart = false;
         bool spaceAppear = false;
         while(*s != '\0')
         {
             if (*s == '.')
             {
                 if (dotAppear || eAppear || spaceAppear)
                     return false;
                 else
                     dotAppear = true;
             }
             else if (*s == 'e' || *s == 'E')
             {
                 if (eAppear || !firstPart || spaceAppear)
                     return false;
                 else
                     eAppear = true;
             }
             else if (isdigit(*s))
             {
                 if (spaceAppear)
                     return false;
                     
                 if (!eAppear)
                     firstPart = true;
                 else
                     secondPart = true;
             }
             else if (*s == '+' || *s == '-')   // behind of e/E
             {
                 if (spaceAppear)
                     return false;
                     
                 if (!eAppear || !(*(s-1) == 'e' || *(s-1) == 'E'))
                     return false;
             }
             else if (isspace(*s))
                 spaceAppear = true;
             else
                 return false;
                 
             s++;            
         }
         
         if (!firstPart) {
             return false;
         }  else if (eAppear && !secondPart) {
             return false;
         } 
         return true;  
    }
};

源码:

Github上的源码

参考:

Leetcode 150题目终结贴 - Valid Number

【leetcode】Valid Number

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/38487239

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();