Saturday, December 29, 2012

[LeetCode] Populating Next Right Pointers in Each Node II 解题报告


Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
  • You may only use constant extra space.
For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
» Solve this problem

[解题思路]
与上一题类似,唯一的不同是每次要先找到一个第一个有效的next链接节点,并且递归的时候要先处理右子树,再处理左子树。


[Code]
1:    void connect(TreeLinkNode *root) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      if(root== NULL) return;  
5:      TreeLinkNode* p = root->next;  
6:      while(p!=NULL)  
7:      {  
8:         if(p->left!=NULL)  
9:         {  
10:            p = p->left;  
11:            break;  
12:        }  
13:        if(p->right!=NULL)  
14:        {  
15:           p = p->right;  
16:           break;  
17:        }  
18:        p = p->next;  
19:      }  
20:      if(root->right!= NULL)  
21:      {        
22:        root->right->next = p;  
23:      }  
24:      if(root->left !=NULL)  
25:      {        
26:        root->left->next = root->right? root->right:p;        
27:      }  
28:      connect(root->right);  
29:      connect(root->left);      
30:    }  


[Note]
1. Line 6, while loop, not if
For example,
 Level 1                      1
                            /              \
 Level 2              2               3
                     /        \                \
 Level 3       4         5                 6
                 /
 Level 4   7

When processing Level 3, while loop is necessary for finding a valid next.


Update 03/09/2014 Add a non-recursion version

1:       void connect(TreeLinkNode *root) {  
2:            TreeLinkNode* cur = root, *next = NULL;  
3:            while(cur!=NULL)  
4:            {  
5:                 TreeLinkNode *p = cur, *k= NULL;  
6:                 while(p!=NULL)  
7:                 {  
8:                      TreeLinkNode* sub = getLinkedLeftNode(p);  
9:                      if(sub != NULL)  
10:                      {  
11:                           if(next == NULL)  
12:                           {  
13:                                next = sub;  
14:                                k = sub;  
15:                           }  
16:                           else  
17:                                k->next = sub;  
18:                           while(k->next !=NULL) // ietrate to the tail  
19:                                k = k->next;  
20:                      }  
21:                      p = p->next;  
22:                 }  
23:                 cur = next;  
24:                 next = NULL;  
25:            }  
26:       }  
27:       TreeLinkNode* getLinkedLeftNode(TreeLinkNode * root)  
28:       {  
29:            if(root->left != NULL && root->right != NULL)  
30:                 root->left->next = root->right;  
31:            if(root->left != NULL)  
32:                 return root->left;  
33:            if(root->right != NULL)  
34:                 return root->right;  
35:            return NULL;  
36:       }  


[LeetCode] Populating Next Right Pointers in Each Node 解题报告


Given a binary tree
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.
Initially, all next pointers are set to NULL.
Note:
  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
» Solve this problem


[解题报告]
当前层处理完next指针的连接以后,再调用下一级节点。

[Code]
1:   void connect(TreeLinkNode *root) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      if(root == NULL) return;  
5:      if(root->left != NULL)  
6:        root->left->next = root->right;  
7:      if(root->right !=NULL)  
8:        root->right->next = root->next? root->next->left:NULL;  
9:       connect(root->left);  
10:       connect(root->right);  
11:    }  



[LeetCode] Plus One 解题报告

Given a number represented as an array of digits, plus one to the number.
» Solve this problem

[解题思路]
加位与进位。模拟。

[Code]
1:  vector<int> plusOne(vector<int> &digits) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int cary=1, sum =0;  
5:      vector<int> result(digits.size(),0);  
6:      for(int i = digits.size()-1; i>=0; i--)  
7:      {        
8:        sum = cary+digits[i];  
9:        cary = sum/10;  
10:        result[i] = sum%10;  
11:      }  
12:      if(cary >0)  
13:      {  
14:        result.insert(result.begin(), cary);  
15:      }  
16:      return result;  
17:    }  


[LeetCode] Permutations II 解题报告


Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].
» Solve this problem

[解题思路]
跟 Permutations的解法一样,就是要考虑“去重”。先对数组进行排序,这样在DFS的时候,可以先判断前面的一个数是否和自己相等,相等的时候则前面的数必须使用了,自己才能使用,这样就不会产生重复的排列了。

与Permitations的code相比,只加了3行,Line 8,23,24。

[Code]
1:    vector<vector<int> > permuteUnique(vector<int> &num) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      vector<vector<int> > coll;  
5:      vector<int> solution;  
6:      if(num.size() ==0) return coll;  
7:      vector<int> visited(num.size(), 0);  
8:      sort(num.begin(), num.end());  
9:      GeneratePermute(num, 0, visited, solution, coll);  
10:      return coll;  
11:    }  
12:    void GeneratePermute(vector<int> & num, int step, vector<int>& visited, vector<int>& solution, vector<vector<int> >& coll)  
13:    {  
14:      if(step == num.size())  
15:      {  
16:        coll.push_back(solution);  
17:        return;  
18:      }  
19:      for(int i =0; i< num.size(); i++)  
20:      {  
21:        if(visited[i] == 0)  
22:        {  
23:          if(i>0 && num[i] == num[i-1] && visited[i-1] ==0)  
24:            continue;  
25:          visited[i] = 1;  
26:          solution.push_back(num[i]);  
27:          GeneratePermute(num, step+1, visited, solution, coll);  
28:          solution.pop_back();  
29:          visited[i] =0;  
30:        }  
31:      }  
32:    }  

[Note]
Line 23: Don't miss “&& visited[i-1] ==0”. Or, the inner recursion will skip using duplicate number.




[LeetCode] Permutations 解题报告


Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].
» Solve this problem

[解题思路]
递归,用标志位记录已使用数字。

[Code]
1:    vector<vector<int> > permute(vector<int> &num) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      vector<vector<int> > coll;  
5:      vector<int> solution;  
6:      if(num.size() ==0) return coll;  
7:      vector<int> visited(num.size(), 0);  
8:      GeneratePermute(num, 0, visited, solution, coll);  
9:      return coll;  
10:    }  
11:    void GeneratePermute(vector<int> & num, int step, vector<int>& visited, vector<int>& solution, vector<vector<int> >& coll)  
12:    {  
13:      if(step == num.size())  
14:      {  
15:        coll.push_back(solution);  
16:        return;  
17:      }  
18:      for(int i =0; i< num.size(); i++)  
19:      {  
20:        if(visited[i] == 0)  
21:        {  
22:          visited[i] = 1;  
23:          solution.push_back(num[i]);  
24:          GeneratePermute(num, step+1, visited, solution, coll);  
25:          solution.pop_back();  
26:          visited[i] =0;  
27:        }  
28:      }  
29:    }  





[LeetCode] Path Sum II 解题报告

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]
» Solve this problem

[解题报告]
二叉树递归。


[Code]
1:    vector<vector<int> > pathSum(TreeNode *root, int sum) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      vector<vector<int> > collect;  
5:      vector<int> solution;  
6:      if(root!=NULL)  
7:        GetPath(root, sum, 0, solution, collect);  
8:      return collect;  
9:    }  
10:    void GetPath(TreeNode* node, int sum, int cal, vector<int>& solution, vector<vector<int> >& collect)  
11:    {   
12:      solution.push_back(node->val);  
13:      cal += node->val;  
14:      if(cal == sum && node->left == NULL && node->right == NULL)  
15:      {  
16:        collect.push_back(solution);        
17:      }  
18:      else  
19:      {      
20:        if(node->left != NULL)  
21:        {        
22:          GetPath(node->left, sum, cal, solution, collect);        
23:        }  
24:        if(node->right != NULL)  
25:        {        
26:          GetPath(node->right, sum, cal, solution, collect);  
27:        }  
28:      }  
29:      solution.pop_back();  
30:      cal -= node->val;  
31:      return;  
32:    }  






Friday, December 28, 2012

[LeetCode] Pascal's Triangle II 解题报告


Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].


[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
Note:
Could you optimize your algorithm to use only O(k) extra space?
» Solve this problem

[解题报告]

把上面的例子变一下型就清楚了

[
 [1],
 [1,1],
 [1,2,1],
 [1,3,3,1],
 [1,4,6,4,1]
]
定义T[i][j]为该三角形i行,第j列的元素,所以可以获得递推函数为


   T[i][j] = T[i-1][j] + T[i-1][j-1] if i>0 && j>0
         Or
            =  1  if i=0
         Or
            =  T[i-1][j]  if j=0

滚动数组实现。注意Line11,要从后往前加,否则会产生冗余计算。

[Code]
1:    vector<int> getRow(int rowIndex) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      vector<int> result;  
5:      result.resize(rowIndex+2);  
6:      for(int i =0; i< rowIndex+2; i++)  
7:        result[i] = 0;  
8:      result[1]=1;  
9:      for(int i =0; i< rowIndex; i++)  
10:      {  
11:        for(int j =rowIndex+1; j>0; j--)  
12:        {  
13:          result[j] = result[j-1] + result[j];  
14:        }  
15:      }  
16:      result.erase(result.begin());  
17:      return result;  
18:    }