Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Monday, August 7, 2017

[Leetcode] Power of Three, Solution

Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?

[Thoughts]
不断的用3来除,如果余数不为0,则判否。


[Code]
1:    bool isPowerOfThree(int n) {  
2:      if(n == 0) return false;  
3:        
4:      if(n == 1) return true;  
5:        
6:      return (n%3 ==0) && isPowerOfThree(n/3);  
7:    }  

followup的问题,如果不用loop或recursion的话,一般都是指数学方法来处理,这里就不花时间了。

[Leetcode] Closest Binary Search Tree Value, Solution

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.
[Thoughts]
遍历二叉搜索树,在遍历的过程中,对于遍历节点记录closest。


[Code]
1:    int closestValue(TreeNode* root, double target) {  
2:      double min = UINT_MAX;  
3:      int closeVal = 0;  
4:        
5:      closest(root, target, min, closeVal);  
6:      return closeVal;  
7:    }  
8:      
9:    void closest(TreeNode* root, double target, double& min, int& closeVal) {  
10:      if(root == NULL) return;  
11:        
12:      if(abs(target - root->val) < min) {  
13:        closeVal = root->val;  
14:        min = abs(target - root->val);  
15:      }  
16:        
17:      if(root->val < target) {  
18:        closest(root->right, target, min, closeVal);  
19:      }else {  
20:        closest(root->left, target, min, closeVal);  
21:      }  
22:    }  



Sunday, April 7, 2013

[LeetCode] Permutation Sequence, Solution


The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
» Solve this problem

[Thoughts]
两个解法。
第一,DFS
递归遍历所有可能,然后累加计算,直至到K为止。

第二,数学解法。

假设有n个元素,第K个permutation是
a1, a2, a3, .....   ..., an
那么a1是哪一个数字呢?

那么这里,我们把a1去掉,那么剩下的permutation为
a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道

设变量K1 = K
a1 = K1 / (n-1)!

同理,a2的值可以推导为
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
 .......
a(n-1) = K(n-1) / 1!
K(n-1) = K(n-2) /2!

an = K(n-1)

实现如下:
1:       string getPermutation(int n, int k) {  
2:            vector<int> nums(n);  
3:            int permCount =1;  
4:            for(int i =0; i< n; i++)  
5:            {  
6:                 nums[i] = i+1;  
7:                 permCount *= (i+1);        
8:            }  
9:            // change K from (1,n) to (0, n-1) to accord to index  
10:            k--;  
11:            string targetNum;  
12:            for(int i =0; i< n; i++)  
13:            {    
14:                 permCount = permCount/ (n-i);  
15:                 int choosed = k / permCount;  
16:                 targetNum.push_back(nums[choosed] + '0');  
17:                 //restruct nums since one num has been picked  
18:                 for(int j =choosed; j< n-i; j++)  
19:                 {  
20:                      nums[j]=nums[j+1];  
21:                 }  
22:                 k = k%permCount;  
23:            }  
24:            return targetNum;  
25:       }  


Sunday, March 3, 2013

[LeetCode] Palindrome Partitioning, Solution


Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
  [
    ["aa","b"],
    ["a","a","b"]
  ]
» Solve this problem

[Thoughts]
这种需要输出所有结果的基本上都是DFS的解法。实现如下。

[Code]
1:       vector<vector<string>> partition(string s) {  
2:            vector<vector<string>> result;  
3:            vector<string> output;  
4:            DFS(s, 0, output, result);  
5:            return result;  
6:       }  
7:       void DFS(string &s, int start, vector<string>& output, vector<vector<string>> &result)  
8:       {      
9:            if(start == s.size())  
10:            {  
11:                 result.push_back(output);  
12:                 return;  
13:            }  
14:            for(int i = start; i< s.size(); i++)  
15:            {    
16:                 if(isPalindrome(s, start, i))  
17:                 {  
18:                      output.push_back(s.substr(start, i-start+1));  
19:                      DFS(s, i+1, output, result);  
20:                      output.pop_back();  
21:                 }  
22:            }  
23:       }  
24:       bool isPalindrome(string &s, int start, int end)  
25:       {  
26:            while(start< end)  
27:            {  
28:                 if(s[start] != s[end])  
29:                 return false;  
30:                 start++; end--;  
31:            }  
32:            return true;  
33:       }  













Saturday, February 2, 2013

[Google] Inorder Successor in Binary Search Tree, Solution


In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inoorder traversal.
In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key greater than the key of input node. So, it is sometimes important to find next node in sorted order.

In the above diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.
Method 1 (Uses Parent Pointer)
In this method, we assume that every node has parent pointer.
The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.
Input: node, root // node is the node whose Inorder successor is needed.
output: succ // succ is Inorder successor of node.
1) If right subtree of node is not NULL, then succ lies in right subtree. Do following.
Go to right subtree and return the node with minimum key value in right subtree.
2) If right sbtree of node is NULL, then succ is one of the ancestors. Do following.
Travel up using the parent pointer until you see a node which is left child of it’s parent. The parent of such a node is the succ.
Implementation
Note that the function to find InOrder Successor is highlighted (with gray background) in below code.
1:  #include <stdio.h>  
2:  #include <stdlib.h>  
3:  /* A binary tree node has data, pointer to left child  
4:    and a pointer to right child */  
5:  struct node  
6:  {  
7:    int data;  
8:    struct node* left;  
9:    struct node* right;  
10:    struct node* parent;  
11:  };  
12:  struct node * minValue(struct node* node);  
13:  struct node * inOrderSuccessor(struct node *root, struct node *n)  
14:  {  
15:   // step 1 of the above algorithm  
16:   if( n->right != NULL )  
17:    return minValue(n->right);  
18:   // step 2 of the above algorithm  
19:   struct node *p = n->parent;  
20:   while(p != NULL && n == p->right)  
21:   {  
22:     n = p;  
23:     p = p->parent;  
24:   }  
25:   return p;  
26:  }  
27:  /* Given a non-empty binary search tree, return the minimum data   
28:    value found in that tree. Note that the entire tree does not need  
29:    to be searched. */  
30:  struct node * minValue(struct node* node) {  
31:   struct node* current = node;  
32:   /* loop down to find the leftmost leaf */  
33:   while (current->left != NULL) {  
34:    current = current->left;  
35:   }  
36:   return current;  
37:  }  
Time Complexity: O(h) where h is height of tree.


Method 2 (Don't Use Parent Pointer)
Inorder travel the tree and
1) If current visit node is target node,  mark the indicator as true.
2) If indicator is true, print the node and return.

Implementation
1:  struct node * inOrderSuccessor(struct node *n, struct node* target, bool& indicator)  
2:  {  
3:   if( n== NULL )  
4:    return NULL;  
5:   if(indicator) return n;  
6:   if(n == target) { indicator = true; return;}  
7:   node* left = inOrderSuccessor(n->left, target, indicator);  
8:   node * right =inOrderSuccessor(n->right, target, indicator);  
9:   if(left != NULL) return left;  
10:   if(right!= NULL) return right;  
11:   return NULL;  
12:  }  

Saturday, December 29, 2012

[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.