Friday, January 1, 2016

267. Palindrome Permutation II ##################

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

Example 1:

Input: "aabb"
Output: ["abba", "baab"]

Example 2:

Input: "abc"
Output: []
A:

每次从一个seed开始, 左右两边加上可能的值。
然后dfs直到都用光。

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        if(s.length() == 0)
            return vector<string>();        
        unordered_map<char,int> M;
        for(auto c:s)
            M[c]++;
        int oddCount = 0;
        char oddCh = '0';
        for(auto iter=M.begin(); iter!=M.end(); iter++){
            if(iter->second %2){
                oddCount++;
                oddCh = iter->first;
            }
        }
        if(oddCount>=2)
            return vector<string>();
        string seed="";
        if(oddCount){
            seed += oddCh;
            M[oddCh]--;
            if(M[oddCh]==0){
                M.erase(oddCh);
            }
        }
        vector<string> res;
        dfs(seed, M,res);
        return res;
    }
private:
    void dfs(string &seed, unordered_map<char,int> &M, vector<string> & res){
        if(M.empty()){
            res.push_back(seed);
            return;
        }
        vector<char> chars; // save a copy, so that we dould not modify on M directly while looping it
        for(auto iter=M.begin();iter!= M.end();iter++){
            chars.push_back(iter->first);
        }
        for(auto ch : chars){
            string tmp(1,ch);
            string newSeed = tmp+ seed + tmp;
            M[ch]-=2;
            if(M[ch]==0)
                M.erase(ch);
            dfs(newSeed, M, res);
            M[ch]+=2; // put them back
        }
    }
};









Mistakes:





Thursday, December 31, 2015

324. Wiggle Sort II

Q:
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
A:

排序,然后分配即可 不行的。 第一个例子就通不过





Mistakes:





Wednesday, December 30, 2015

266. Palindrome Permutation ----------E

Given a string, determine if a permutation of the string could form a palindrome.

Example 1:

Input: "code"
Output: false

Example 2:

Input: "aab"
Output: true

Example 3:

Input: "carerac"
Output: true
A:

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> M;
        for(auto c : s)
            M[c]++;
        int oddCount = 0;
        for(auto iter = M.begin(); iter!= M.end(); iter++){
            if(iter->second %2)
                oddCount++;
        }
        return oddCount<=1;
    }
};

Mistakes:





265. Paint House II

There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Example:

Input: [[1,5,3],[2,9,4]]
Output: 5
Explanation: Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; 
             Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. 

Follow up:
Could you solve it in O(nk) runtime?

A:
DP
每次记录之前一行,最小的value和index,以及 secondMinimum value;

class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        int n = costs.size();
        if(n==0)
            return 0;
        int k = costs[0].size();
        int minVal = 0, minIndex=0;
        int min2Val = 0; // no need to record its index
        for(auto & cost : costs){
            int newMinVal = INT_MAX-1, newMinIndex=0;
            int newMin2Val = INT_MAX;
            for(int i =0;i<k;i++){
                cost[i] += (i != minIndex ? minVal : min2Val);
                if(cost[i] < newMin2Val){
                    newMin2Val = cost[i];
                }
                if(cost[i] < newMinVal){
                    newMin2Val = newMinVal;
                    newMinVal = cost[i];
                    newMinIndex = i;
                }
            }
            minVal = newMinVal;
            minIndex = newMinIndex;
            min2Val = newMin2Val;
        }
        return minVal;
    }
};

不用单独把 第0行单独计算(只需要把minValue = 0 即可)

Mistakes:






261. Graph Valid Tree ------------M

Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

Example 1:

Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true

Example 2:

Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false

Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.


A:
首先,# of edges = # of nodes - 1        (还是必要的,否则可能是个有环联通图)
然后: 检查是否从一个点可以发现其余所有的node

class Solution {
public:
    bool validTree(int n, vector<vector<int>>& edges) {
        if(edges.size() !=n-1)
            return false;
        unordered_map<int,vector<int>> M;
        for(auto &edge : edges){
            M[edge[0]].push_back(edge[1]);
            M[edge[1]].push_back(edge[0]);
        }
        vector<bool> visited(n,false);
        dfs(0, M, visited);// pick any node, and 
        for(auto v:visited)
            if(not v) // if some nodes are not visited
                return false;
        return true;
    }
private:
    void dfs(int seed, unordered_map<int,vector<int>> &M,vector<bool> &visited){
        if(visited[seed])// if already visted at this place
            return;
        visited[seed]=true;
        for(auto v : M[seed])
            dfs(v,M, visited);
    }
};
Mistakes:
1: 要把双向的edges都放到Map里面




Tuesday, December 29, 2015

256. Paint House ---------E

There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.

The cost of painting each house with a certain color is represented by a n x 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

Example:

Input: [[17,2,17],[16,16,5],[14,3,19]]
Output: 10
Explanation: Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. 
             Minimum cost: 2 + 5 + 3 = 10.
A:
DP

class Solution {
public:
    int minCost(vector<vector<int>>& costs) {
        int n = costs.size();
        if(n==0)
            return 0;
        for(int i =1;i<n;i++){
            costs[i][0] += min( costs[i-1][1], costs[i-1][2]);
            costs[i][1] += min( costs[i-1][0], costs[i-1][2]);
            costs[i][2] += min( costs[i-1][0], costs[i-1][1]);
        }
        return min(costs[n-1][0], min(costs[n-1][1], costs[n-1][2] ));
    }
};


255. Verify Preorder Sequence in Binary Search Tree ----------M !!!!!~~~~~~

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

Consider the following binary search tree: 

     5
    / \
   2   6
  / \
 1   3

Example 1:

Input: [5,2,6,1,3]
Output: false

Example 2:

Input: [5,2,1,3,6]
Output: true

Follow up:
Could you do it using only constant space complexity?

A:

每次找到小于的, 然后分开查询

class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        return helper(preorder, 0, preorder.size()-1);
    }
private:
    bool helper(vector<int>& preorder, int start, int end){
        if(start >= end) // just one value
            return true;
        int val = preorder[start];
        int mid = start+1; // mid point to first position either go-beyond, or with bigger value 
        while(mid<=end && preorder[mid] < val){
            mid++;
        }
        for(int i = mid; i<=end;i++){
            if(preorder[i] < val )
                return false;
        }
        return helper(preorder, start+1,mid-1) && helper(preorder, mid, end);
    }
};
上面这个方法,说都通过了,可是有点儿慢。   修改下,加上范围. 这样,可以省掉上面的for循环
class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        return helper(preorder, 0, preorder.size()-1, INT_MIN, INT_MAX);
    }
private:
    bool helper(vector<int>& preorder, int start, int end, int lower, int upper){
        if(start > end) // just one value
            return true;
        int val = preorder[start];
        if(val <=lower || val >= upper)
            return false;
        if(start == end)
            return true;
        int mid = start+1; // mid point to first position either go-beyond, or with bigger value 
        while(mid<=end && preorder[mid] < val){
            if(preorder[mid]<=lower)
                return false;
            mid++;
        }
        return helper(preorder, start+1,mid-1, lower, val) && helper(preorder, mid, end, val, upper);
    }
};
这次通过了, 可是,只是faster than 5.65% 
观察得知,我们还是有了个while 循环,考虑去掉。  用stack 来表示。

This problem is very interesting. Recursive approach is very straightforward, though solution is likely of O(nlogn)/O(logn) time/space complexity (avg), or O(N^2)/O(N) worst case.


The key to optimize is to recall how iterative(non-recursive)

pre-order traversal works, then follow the same idea to "reconstruct" BST from preorder sequence, during which we need a stack to keep track of node path from root. The trick here is to use input preorder sequence to simulate the stack in-place. For verification purpose, we need to maintain a "lower bound" variable: when we visit a node that is the right child of its parent, the parent's value must be lower bound of all subsequent values.

class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        stack<int> st;
        int lower_bound = INT_MIN;
        for(int i = 0;i< preorder.size();i++){
            int v = preorder[i];
            if(v <= lower_bound) // check that it's in the range
                return false;
            
            if(st.empty() || v < st.top()){
                st.push(v);
            }else{
                lower_bound = st.top();
                st.pop();
                i--;     // this is the KEY, step back so we can check with grandparent 
            }
        }
        return true;
    }
};


Mistakes: