2016年2月26日 星期五

LEET code -- Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?


下面這寫法要額外空間

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int size=matrix.size();
        vector<vector<int>> co(size,vector<int>(size,0));
        co=matrix;
        for(int i=0;i<size;i++){
            for(int j=0;j<size ;j++){
                matrix[j][size-i-1]=co[i][j];
            }
        }
    }
};

------------
每次轉四個角落
一起轉  不用額外空間

要注意邊界
左上 是 col會跑
左下  是row會跑
右上 是row會跑
右下 是col會跑


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int size=matrix.size();
        for(int row=0;row<size/2;row++){
            for(int col=row;col<size-1-row;col++){
                int temp=matrix[row][col];//left up
                matrix[row][col]=matrix[size-1-col][row];//left button
                matrix[size-1-col][row]=matrix[size-1-row][size-1-col];//right button
                matrix[size-1-row][size-1-col]=matrix[col][size-1-row];//right up
                matrix[col][size-1-row]=temp;
            }
        }

    }
};

LEET code -- Sort Colors

 Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You are not suppose to use the library's sort function for this problem.


如果current 當下不等於 i (顏色)
就往後找  看有沒有  如果找不到就換 下一個顏色

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int current=0;
        int size=nums.size();
        for(int i=0;i<3;i++){
            int color=current;
            while(color<size && current<size){
                if(nums[current]!=i){
                    color=current+1;
                    while(color<size && nums[color]!=i)color++;
                    if(color<size){
                        int temp=nums[color];
                        nums[color]=nums[current];
                        nums[current]=temp;
                    }else break;
                }
                current++;
                
            }
        }
    }
};




-----------


The solution requires the use of tracking 3 positions, the Low, Mid and High.
We assume that the mid is the "Unknown" area that we must evaluate.
If we encounter a 0, we know that it will be on the low end of the array, and if we encounter a 2, we know it will be on the high end of the array.
To achieve this in one pass without preprocessing (counting), we simply traverse the unknown will generating the low and high ends.
Take this example:
Assume our input is: 1 0 2 2 1 0 (short for simplicity).

Running the algorithm by hand would look something like:

    1 0 2 2 1 0
    ^         ^
    L         H
    M

    Mid != 0 || 2
    Mid++

    1 0 2 2 1 0
    ^ ^       ^
    L M       H

    Mid == 0
    Swap Low and Mid
    Mid++
    Low++

    0 1 2 2 1 0
      ^ ^     ^
      L M     H

    Mid == 2
    Swap High and Mid
    High--

    0 1 0 2 1 2
      ^ ^   ^
      L M   H

    Mid == 0
    Swap Low and Mid
    Mid++
    Low++

    0 0 1 2 1 2
        ^ ^ ^
        L M H

    Mid == 2
    Swap High and Mid
    High--

    0 0 1 1 2 2
        ^ ^
        L M
          H

    Mid <= High is our exit case



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
    public:
    void sortColors(vector<int>& nums) 
    {
        int tmp = 0, low = 0, mid = 0, high = nums.size() - 1;

        while(mid <= high)
        {
            if(nums[mid] == 0)
            {
                tmp = nums[low];
                nums[low] = nums[mid];
                nums[mid] = tmp;
                low++;
                mid++;
            }
            else if(nums[mid] == 1)
            {
                mid++;
            }
            else if(nums[mid] == 2)
            {
                tmp = nums[high];
                nums[high] = nums[mid];
                nums[mid] = tmp;
                high--;
            }
        }
    }
};

LEET code -- Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

就是找出DFS他parse的順序找出來

為了可以提早結束  我用-1代表找到
rank代表現在找到第幾個數字了


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        if(root==NULL)return 0;
        rank=0;
        DFS(root,k);
        return reuslt;
        
    }
    int DFS(TreeNode* root,int level){
        if(root==NULL)return rank;
        int left=DFS(root->left,level);
        if(left<0)return -1;
        rank=rank+1;
        if(level==rank){
            reuslt=root->val;
            return -1;
        }
        int right=DFS(root->right,level);
        if(right <0)return -1;
        return 1;
    }
private:
    int rank;
    int reuslt;
};

--------------------------


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    TreeNode* current = NULL;
    stack<TreeNode*> s;
    int kthSmallest(TreeNode* root, int k) {
        current = root;
        int count = 1;
        while(1)
        {
        while(current)
        {
            s.push(current);
            current = current->left;
        }
        if(count == k)
        {
            TreeNode* node = s.top();
            return node->val;
        }
        if(count != k)
        {
            TreeNode* node = s.top();
            s.pop();
            current = node->right;
            count++;
        }
        }
    }
};


LEET code -- Permutations

 Given a collection of distinct 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].


印出所有的排列組合,使樣回朔法來跑

用一個boo;陣列來記錄那些數字用過了
接著丟給下一個去紀錄


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    void find(vector<vector<int>> &ans, vector<int> &current, vector<int> &nums, bool *use){
        if(current.size() == nums.size()){
            ans.push_back(current);
            return ;
        }
        for(int i=0;i<nums.size();i++){
            if(use[i]==false){
                current.push_back(nums[i]);
                use[i]=true;
                find(ans,current,nums,use);
                current.pop_back();
                use[i]=false;
            }
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        int size=nums.size();
        bool use[size]={0};
        vector<vector<int>> ans;
        vector<int> current;
        find(ans,current,nums,use);//not &use
        //for(int i=0;i<size;i++)use[i]=false;
        return ans;
    }
};

--------------------
旋轉的方式



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        create(nums,res,0);
        return res;
    }

    void create(vector<int>& nums,vector<vector<int>> &res,int n)
    {
        if(n==nums.size()-1)
            res.push_back(nums);
        else
        {
            for(int i=n;i<nums.size();i++)
            {
                swap(nums[i],nums[n]);
                create(nums,res,n+1);
                swap(nums[i],nums[n]);
            }
        }
    }

    void swap(int &a,int &b)
    {
        int tmp=a;
        a=b;
        b=tmp;
    }
};

LEET code -- 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:

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



下面利用Backtracking的方式  我現在選擇( 後面的選擇丟給下一個recursive來決定
leftsize代表有多少(   這個數目不能超過n
rightsize代表有多少)   這個數目不能超過(

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string s="(";
        findparent(ans,s,1,0,n);
        return ans;
    }
    
    void findparent(vector<string> &ans, string s,int leftsize,int rightsize,int n){//left is (   right is )
        if(n*2==leftsize+rightsize){
            ans.push_back(s);
            return;
        }
        if(leftsize<n)findparent(ans,s+"(",leftsize+1,rightsize,n);
        if(rightsize<leftsize)findparent(ans,s+")",leftsize,rightsize+1,n);
        
    }
};


-----------------------








-------------------------

神人iterater

logic here is simple:
First, store a result vector, then for every entry:
  • add '(', when cannot add ')'
  • add ')', when cannot add '('
  • copy this entry and add '(' and ')' separately to original and new copy, when both are valid
here count and countleft are vectors that store check values.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result(1);
        vector<int> count(1,0),countleft(1,0);
        for(int i=0;i<2*n;++i){
            int m=count.size();
            for(int j=0;j<m;++j){
                if(count[j]==0){
                    result[j]+='(';
                    count[j]++;
                    countleft[j]++;
                }
                else if(countleft[j]==n) result[j]+=')';
                else{
                    result.push_back(result[j]+')');
                    count.push_back(count[j]-1);
                    countleft.push_back(countleft[j]);
                    result[j]+='(';
                    count[j]++;
                    countleft[j]++;
                }
            }
        }
        return result;
    }
};








LEET code -- Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,
Consider the following matrix:
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.





可以發現  每一排的最後右邊一定最大
所以可以先搜尋 最右邊 去找要搜尋哪一排

但是我找到那排是用for loop找  會太慢  可以改成binary search


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        for(int i=0;i<matrix.size();i++){
            if(target <=matrix[i][ matrix[i].size()-1 ] ){
                for(int j=0;j<matrix[i].size();j++){
                    if(target == matrix[i][j])return true;
                }
                return false;
            }
        }
        return false;
    }
};

-------------
用binary search



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        
        for(int i=0;i<matrix.size();i++){
            if(target <=matrix[i][ matrix[i].size()-1 ] ){
                int start=0,end=matrix[i].size()-1;
                while(start<=end){
                    int mid = start +(end-start)/2;//prevent overflow
                    if(matrix[i][mid]==target)return true;
                    if(matrix[i][mid] > target)end=mid-1;
                    else start=mid+1;
                }
                return false;
            }
        }
        return false;
    }
};





LEET code -- Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]


confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


queue 的STL 注意是push 跟front 還有pop

reverse也是STL


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;//initial ,empty
        queue<TreeNode*> parse;
        if(root==NULL)return ans;
        parse.push(root);
        while(parse.size()>0){
            vector<int> level;//local level
            for(int i=parse.size();i>0;i--){
                TreeNode * front = parse.front();
                level.push_back(front->val);
                if(front->left!=NULL)parse.push(front->left);
                if(front->right!=NULL)parse.push(front->right);
                parse.pop();
            }
            ans.push_back(level);
            
        }
        reverse(ans.begin(),ans.end());
        
    }
};

---------------------------
recursive



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:

    vector< vector<int> > result;

    void dfs(TreeNode *root, int level)
    {
        if(!root) return;

        if(level == result.size()) 
            result.push_back( vector<int>() );

        vector<int> &vec = result[level];
        vec.push_back(root->val);

        dfs(root->left, level+1);
        dfs(root->right, level+1);
    }

    vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        if(!root) return vector< vector<int> >();

        dfs(root, 0);

        return vector< vector<int> >(result.rbegin(), result.rend());
    }
};