Showing posts with label bit. Show all posts
Showing posts with label bit. Show all posts

Monday, November 12, 2018

308. Range Sum Query 2D - Mutable

308Range Sum Query 2D - Mutable
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
Note:
  1. The matrix is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRegion function is distributed evenly.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.
----------------------------------------------
需要与面试官沟通 
read heavy - 那就正常写,矩阵里面直接存cumulative sum. 读是O(1), 写是O(m * n)

write heavy -  bit, 读写都是O(log m * log n)

Solution #1 Binary index tree,
class NumMatrix {

    private int[][] bit;
    private int[][] matrix;
    private int m;
    private int n;
    public NumMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return;
        m = matrix.length;
        n = matrix[0].length;
        bit= new int[m + 1][n + 1];
        this.matrix = new int[m][n];
        initBit(matrix);
    }
    
    private void initBit(int[][] matrix) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                update(i, j, matrix[i][j]);
            }
        }
        
    } 
    
    public void update(int row, int col, int val) {
        if (m == 0 || n == 0) return;
        int delta = val - matrix[row][col];
        matrix[row][col] = val;
        row++;
        col++;
        
        while (row <= m) {
            updateY(row, col, delta);
            row += (row & -row);
        }
    }
    
    public void updateY(int row, int col, int val) {
        while (col <= n) {
            bit[row][col] += val;
            col += (col & -col);   
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (m == 0 || n == 0) return 0;
        return read(row2, col2) - read(row2, col1 - 1) - read(row1 - 1, col2) + read(row1 - 1, col1 - 1);
    }
    
    public int read(int row, int col) {
        row++;
        col++;
        int rt = 0;
        
        while (row > 0) {
            rt += readY(row, col);
            row -= (row & -row);
        }
        
        return rt;
    }
    
    public int readY(int row, int col) {
        int rt = 0;
        while (col > 0) {
            rt += bit[row][col];
            col -= (col & -col);
        }
        
        return rt;
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * obj.update(row,col,val);
 * int param_2 = obj.sumRegion(row1,col1,row2,col2);
 */

Thursday, July 9, 2015

Day 116, #231, #232, #234, Power of Two, Implement Queue using Stacks, Palindrome Linked List, Number of Digit One

Power of Two
Given an integer, write a function to determine if it is a power of two.
----------------------------------------------------------------------
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        return !(n & (n - 1));
    }
};

Implement Queue using Stacks
Implement the following operations of a queue using stacks.
  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
---------------------------------------------
只有当output stack为空时,才会将input里的数全部压入output,抄的
class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        input.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        peek();
        output.pop();
    }

    // Get the front element.
    int peek(void) {
        if (output.empty()) {
            while (!input.empty()) {
                output.push(input.top());
                input.pop();
            }
        }
        return output.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return input.empty() && output.empty();
    }
private:
    stack<int> input;
    stack<int> output;
};

Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
-----------------------------------------------
找到中点,翻转其中一半,再比较
slow是中点(odd number)或者是后半部分的启示(even)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (head == NULL) return true;
        ListNode *fast = head, *slow = head;
        while (fast != NULL) {
            fast = fast->next;
            if (fast != NULL) {
                fast = fast->next;
                slow = slow->next;
            }
        }
        
        // reverse the second half
        ListNode *newHead = NULL;
        while (slow != NULL) {
            ListNode *temp = slow->next;
            slow->next = newHead;
            newHead = slow;
            slow = temp;
        }
        
        while (newHead != NULL) {
            if (newHead->val != head->val) return false;
            newHead = newHead->next;
            head = head->next;
        }
        
        return true;
    }
};

Number of Digit One
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
Hint:
  1. Beware of overflow.
--------------------------------------------------------------
对每一位上的1可能出现的次数进行统计
refhttp://blog.csdn.net/xudli/article/details/46798619
class Solution {
public:
    int countDigitOne(int n) {
        int rt = 0;
        
        for (long long i = 1; i <= n; i *= 10) {
            int left = n / i;
            int right = n % i; // 当前位之后的数
            int cur = left % 10; // 当前位上的数
            left /= 10;  // 当前位之前的数
            
            if (cur == 0) {
                rt += left * i;
            }else if (cur == 1) {
                rt += left * i + right + 1;
            }else {
                rt += (left + 1) * i;
            }
        }
        
        return rt;
    }
};

Thursday, June 11, 2015

Day 105, ##, Binary Tree Right Side View, Number of Islands , Bitwise AND of Numbers Range, Happy Number, Remove Linked List Elements, Isomorphic Strings

Binary Tree Right Side View 
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].
-------------------------------------------------------
Similar to level order traversal
can be done iteratively with a queue

/**
 * 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:
    void side(vector<int> &rt, int level, TreeNode *root) {
        if (root == NULL) {
            return;
        }
        
        if (rt.size() < level) {
            rt.push_back(root->val);
        }else {
            rt[level - 1] = root->val;
        }
        
        side(rt,level + 1, root->left);
        side(rt,level + 1, root->right);
    }

    vector<int> rightSideView(TreeNode* root) {
        vector<int> rt;
        side(rt,1,root);
        return rt;
    }
};

Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
------------------------------------------------------
Solution #1 dfs
class Solution {
public:
    void dfs(vector<vector<char>>& grid, vector<vector<bool> > &visit, int row, int col) {
        if (row < 0 || row >= visit.size() || col < 0 || col >= visit[0].size() || visit[row][col] || grid[row][col] == '0') return;
        
        visit[row][col] = true;
        dfs(grid,visit,row + 1, col);
        dfs(grid,visit,row - 1, col);
        dfs(grid,visit,row, col + 1);
        dfs(grid,visit,row, col - 1);
    }

    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        if (m == 0) return 0;
        int n = grid[0].size();
        vector<vector<bool> > visit(m,vector<bool>(n,false));
        int count = 0;
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visit[i][j] && grid[i][j] == '1') {
                    count++;
                    dfs(grid,visit,i,j);
                }
                
            }
        }
        
        return count;
    }
};
Solution #2 bfs
class Solution {
public:
    void bfs(vector<vector<char>>& grid, vector<vector<bool> > &visit, int row, int col) {
        queue<pair<int,int> > que;
        que.push(make_pair(row,col));
        visit[row][col] = true;
        
        while (!que.empty()) {
            pair<int,int> point = que.front();
            que.pop();
            row = point.first;
            col = point.second;
            
            if (row + 1 < visit.size() && !visit[row + 1][col] && grid[row + 1][col] == '1') {
                que.push(make_pair(row + 1,col));
                visit[row + 1][col] = true;
            }
            
            if (row - 1 >= 0 && !visit[row - 1][col] && grid[row - 1][col] == '1') {
                que.push(make_pair(row - 1,col));
                visit[row - 1][col] = true;
            }
            
            if (col - 1 >= 0 && !visit[row][col - 1] && grid[row][col - 1] == '1') {
                que.push(make_pair(row,col - 1));
                visit[row][col - 1] = true;
            }
            
            if (col + 1 < visit[0].size() && !visit[row][col + 1] && grid[row][col + 1] == '1') {
                que.push(make_pair(row,col + 1));
                visit[row][col + 1] = true;
            }
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        int m = grid.size();
        if (m == 0) return 0;
        int n = grid[0].size();
        vector<vector<bool> > visit(m,vector<bool>(n,false));
        int count = 0;
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!visit[i][j] && grid[i][j] == '1') {
                    bfs(grid,visit,i,j);
                    count++;
                }
            }
        }
        
        return count;
    }
};

Bitwise AND of Numbers Range
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
---------------------------------------
The idea is very simple:
  1. last bit of (odd number & even number) is 0.
  2. when m != n, There is at least an odd number and an even number, so the last bit position result is 0.
  3. Move m and n rigth a position.
Keep doing step 1,2,3 until m equal to n, use a factor to record the iteration time.
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int count = 0;
        while (m != n) {
            m >>= 1;
            n >>= 1;
            count++;
        }
        
        return m << count;
    }
};
Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
----------------------------------------------
class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> s;
        
        while (s.find(n) == s.end()) {
            if (n == 1) return true;
            s.insert(n);
            
            int sum = 0;
            while (n != 0) {
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            n = sum;
        }
        
        return false;
    }
};

Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
--------------------------------------------------------
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *itr = dummy;
        
        while (itr->next != NULL) {
            if (itr->next->val == val) {
                itr->next = itr->next->next;
            }else {a
                itr = itr->next;
            }
        }
        
        return dummy->next;
    }
};

Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg""add", return true.
Given "foo""bar", return false.
Given "paper""title", return true.
Note:
You may assume both s and t have the same length.
--------------------------------------------
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        vector<char> dicS(256,'\0');
        vector<char> dicT(256,'\0');
        
        for (int i = 0; i < s.length(); i++) {
            if (dicS[s[i]] == '\0' && dicT[t[i]] == '\0') {
                dicS[s[i]] = t[i];
                dicT[t[i]] = s[i];
            }else if (dicS[s[i]] != t[i] || dicT[t[i]] != s[i]) {
                return false;
            }    
        }
        
        return true;
    }
};

Reverse Linked List
Reverse a singly linked list. 
----------------------------------------------------------------
Iterative
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *newHead = NULL;
        while (head != NULL) {
            ListNode *temp = head->next;
            head->next = newHead;
            newHead = head;
            head = temp;
        }
        
        return newHead;
    }
};
Recursive
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *rev(ListNode* head, ListNode * newHead) {
        if (head == NULL) return newHead;
        ListNode *temp = head->next;
        head->next = newHead;
        return rev(temp,head);
    }

    ListNode* reverseList(ListNode* head) {
        return rev(head,NULL);
    }
};

Wednesday, June 10, 2015

Day 104, ##, Best Time to Buy and Sell Stock IV, Count Primes, Rotate Array,Reverse Bits, Number of 1 Bits, House Robber

Best Time to Buy and Sell Stock IV
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
-----------------------------------------------------------------------------
Solution #1, global[i][j] has the max profit at at most j transaction in i days, local[i][j] has the max profit at at most j transaction in i + 1 days and the last transaction must sell at ith day

local[i][j] = max(global[i -1][j - 1] + max(diff,0), local[i - 1][j] + diff)
global[i][j] = max(global[i - 1][j],local[i][j])

local[i - 1][j] + diff推导:
prices[i] - prices[i - 2] = (prices[i - 1] - prices[i - 2]) + (prices[i] - prices[i - 1])
reference: http://blog.csdn.net/linhuanmars/article/details/23236995

class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        if (prices.size() == 0 || k == 0) return 0;
        if (k > prices.size()) {
            return basicSol(prices);
        }
        
        vector<vector<int> > local(prices.size(),vector<int>(k + 1,0));
        vector<vector<int> > global(prices.size(),vector<int>(k + 1,0));
        
        for (int i = 1; i < prices.size(); i++) {
            for (int j = 1; j <= k; j++) {
                int diff = prices[i] - prices[i - 1];
                local[i][j] = max(global[i -1][j - 1] + max(diff,0), local[i - 1][j] + diff);
                global[i][j] = max(global[i - 1][j],local[i][j]);
            }
        }
        
        return global[prices.size() - 1][k];
    }
    
    int basicSol(vector<int>& prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); i++) {
            res += max(0,prices[i] - prices[i - 1]);
        }
        return res;
    }
    
};

Solution #2, space optimization
'cause of global[j - 1], inner loop goes backwards
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        if (prices.size() == 0 || k == 0) return 0;
        if (k > prices.size()) {
            return basicSol(prices);
        }
        
        vector<int> local(k + 1,0);
        vector<int> global(k + 1,0);
        
        for (int i = 1; i < prices.size(); i++) {
            int diff = prices[i] - prices[i - 1];
            for (int j = k; j > 0; j--) {
                local[j] = max(global[j - 1] + max(diff,0), local[j] + diff);
                global[j] = max(global[j],local[j]);
            }
        }
        
        return global[k];
    }
    
    int basicSol(vector<int>& prices) {
        int res = 0;
        for (int i = 1; i < prices.size(); i++) {
            res += max(0,prices[i] - prices[i - 1]);
        }
        return res;
    }
    
};

Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n.
---------------------------------------------------------------------------
details is on OJ
class Solution {
public:
    int countPrimes(int n) {
        vector<bool> isPrime(n, true);
        
        for (int i = 2; i * i < n; i++) {
            if (!isPrime[i]) continue;
            for (int j = i * i; j < n; j += i) {
                isPrime[j] = false;
            }
        }
        
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (isPrime[i]) {
                count++;
            }
        }
        
        return count;
    }
};
Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Related problem: Reverse Words in a String II
---------------------------------------------------------------
三步翻转
class Solution {
public:
    void rotateHelper(vector<int>& nums, int start, int end) {
       for (int i = 0; i < (end - start + 1) / 2; i++) {
            int temp = nums[i + start];
            nums[i + start] = nums[end - i];
            nums[end - i] = temp;
        }
    }

    void rotate(vector<int>& nums, int k) {
        k %= nums.size();
        rotateHelper(nums,0,nums.size() - k - 1);
        rotateHelper(nums,nums.size() - k, nums.size() - 1);
        rotateHelper(nums,0,nums.size() - 1);
    }
};

Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
----------------------------------
read: http://articles.leetcode.com/2011/08/reverse-bits.html
class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t rt = 0;
        for (int i = 0; i < 32; i++) {
            rt <<= 1;
            if (n & 1) {
                rt += 1;
            }
            n >>= 1;
        }
        
        return rt;
    }
};

Number of 1 Bits
only count ones, not zeros
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n) {
            n = n & n - 1;
            count++;
        }
        
        return count;
    }
};
House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
-------------------------------------------------
DP, dp[i] has the max profit [0 : i] and i is robbed
O(n) space
class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n + 2,0);
        for (int i = n - 1; i >= 0; i--) {
            dp[i] = max(nums[i] + dp[i + 2],dp[i + 1]);
        }
        
        return dp[0];
    }
};

递归:发现重复子问题,所以DP
int rob(vector<int> &houses,int i) {
    if (i == houses.size()) return 0;
    if (i == houses.size() - 1) {
        return houses[i];
    }
    
    return max(houses[i] + rob(houses,i + 2),rob(houses,i + 1));
}

Optimized, O(1) space
class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        int pre1 = 0,pre2 = 0;
        for (int i = n - 1; i >= 0; i--) {
            int cur = max(nums[i] + pre2,pre1);
            pre2 = pre1;
            pre1 = cur;
        }
        
        return pre1;
    }
};

Tuesday, December 31, 2013

Day 71, ##, Single Number, Single Number II

Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
------------------------------------------------------------
XOR
we know A^A = 0 and A^A^B  == A^B^A == B;
class Solution {
public:
    int singleNumber(int A[], int n) {
        int ret = 0;
        for (int i = 0; i < n; i++) {
            ret = ret ^ A[i];
        }
        return ret;
    }
};
Update on Dec-26-2014
other solutions:
#1 hashmap
#2 sort
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
-----------------------------------------------------------------
Solution #1
Consider all numbers in binary format. Using an array to contain the result of bits count mod by 3
class Solution {
public:
    int singleNumber(int A[], int n) {
        vector<int> v(32,0);
        int ret = 0;
        for (int i = 0; i < 32; i++) {
            for (int j = 0; j < n; j++) {
                if ((A[j] >> i) & 1) {
                    v[i] = (v[i] + 1) % 3;
                }
            }
            ret |= (v[i] << i); 
        }
        return ret;
    }
};
Update on Dec-26-2014
vector can be replaced with a single variable
Solution #2
one contains bits that are shown once, two is for twice.
on
class Solution {
public:
    int singleNumber(int A[], int n) {
        int one = 0, two = 0, three = 0;
        for (int i = 0; i < n; i++) {
            two = two | (one & A[i]); // plus bits shown in both one and A[i], now two may contain bits that show 3 times 
            one = one ^ A[i]; // discard bits that have been shown twice
            three = ~ (one & two); // find bits that are in both one and two, then invert them
            
            // discard bits that have been shown 3 times
            one = one & three; 
            two = two & three;
        }
        return one;
    }
};
COME_BACK
https://leetcode.com/discuss/6632/challenge-me-thx
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int one = 0, two = 0;
        for (int i = 0; i < nums.size(); i++) {
            one = ~two & (nums[i] ^ one);
            two = ~one & (nums[i] ^ two);
        }
        
        return one;
    }
};

Friday, December 20, 2013

Day 60, #51, #52, #54, N-Queens, N-Queens II, Spiral Matrix

N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
----------------------------------------------------------------------
Typical DFS. Set up 3 vector<bool>s to indicate conflict
Red is backslash
Blue is slash
Green is row


class Solution {
public:
    void queens(vector<vector<string> > &ret,vector<bool> &slash, vector<bool> &backslash, vector<bool> &usedRow, vector<string> cur, int col, int n) {
        if (col == n) {
            ret.push_back(cur);
            return;
        }

        for (int row = 0; row < n; row++) {

            // check conflicts in diagonals and same row
            if (slash[col + row] && backslash[row-col + n] && usedRow[row]) {
                cur[row][col] = 'Q';
                slash[col + row] = false;
                backslash[row-col + n] = false;
                usedRow[row] = false;
                queens(ret,slash,backslash,usedRow,cur,col+1,n);
                
                // backtrack
                cur[row][col] = '.';
                slash[col + row] = true;
                backslash[row-col + n] = true;
                usedRow[row] = true;
            }
        }
    }

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > ret;
        vector<bool> slash(n*2,true);
        vector<bool> backslash(n*2,true);
        vector<bool> usedRow(n,true);
        
        // populate vectors
        string str = "";
        for (int i = 0; i < n; i++) {
            char c = '.';
            str += c;
        }
        vector<string> cur(n,str);
        
        queens(ret,slash,backslash,usedRow,cur,0,n);
        return ret;
    }
};
Update Feb-10-2015
Using bit operation
class Solution {
public:
    string getString(int n, int p) {
        string s(n,'.');
        s[p] = 'Q';
        return s;
    }

    void queens(vector<vector<string> > &rt, vector<string> cur,int slash, int backSlash, int row, int n) {
        int upperLimit = (1 << n) - 1;
        if (row == upperLimit) {
            rt.push_back(cur);
            return;
        }
        
        int possiblePositions = upperLimit & (~(slash | backSlash | row));
        int itr = possiblePositions;
        int p = n - 1;
        while (possiblePositions != 0) {
            int rightMost = possiblePositions & (-possiblePositions);
            if (itr & 1) {
                string s = getString(n,p);
                vector<string> temp = cur;
                temp.push_back(s);
                possiblePositions -= rightMost;
                
                queens(rt,temp,(slash + rightMost) << 1,(backSlash + rightMost) >> 1,row + rightMost,n);
            }
            p--;
            itr >>= 1;
        }
    }

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > rt;
        vector<string> cur;
        queens(rt,cur,0,0,0,n);
        
        return rt;
    }
};

Java, updated on Sep-8th-2018
O(n!)
T(n) = n * T(n - 1)

class Solution {
    public List> solveNQueens(int n) {
        boolean[] cols = new boolean[n];
        boolean[] diag = new boolean[n * 2]; // row + col
        boolean[] antiDiag = new boolean[n * 2]; // row - col + n - 1
        
        List> rt = new ArrayList<>();
        dfs(0, n, new ArrayList(), rt, cols, diag, antiDiag);
        
        return rt;
    }
    
    private void dfs(int row, int n, List sofar, List> rt,
                    boolean[] cols, boolean[] diag, boolean[] antiDiag) {
        
        if (row >= n) {
            rt.add(sofar);
            return;
        }
                
        String cur = "";
        for (int i = 0; i < n; i++) {
            if (!cols[i] && !diag[row + i] && !antiDiag[row - i + n - 1]) {
                cols[i] = true;
                diag[row + i] = true;
                antiDiag[row - i + n - 1] = true;
            
                String tmp = cur + "Q";
                for (int j = i + 1; j < n; j++) tmp += "."; 
                List tmpSofar = new ArrayList<>(sofar);
                tmpSofar.add(tmp);
                
                dfs(row + 1, n, tmpSofar, rt, cols, diag, antiDiag);
                
                cols[i] = false;
                diag[row + i] = false;
                antiDiag[row - i + n - 1] = false;
            }
            
            cur += ".";
        }
    }
}

N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
---------------------------------------------------------------------
Solution #1 similar to previous problem
Note that usedRow[row] should be checked first otherwise it exceeds OJ's  time limit
class Solution {
public:
void queens(int &ret,vector<bool> &slash, vector<bool> &backslash, vector<bool> &usedRow, int col, int n) {
        if (col == n) {
            ret++;
            return;
        }

        for (int row = 0; row < n; row++) {
            if (usedRow[row] && slash[col + row] && backslash[row-col + n]) {
                slash[col + row] = false;
                backslash[row-col + n] = false;
                usedRow[row] = false;
                queens(ret,slash,backslash,usedRow,col+1,n);
                
                // backtrack
                slash[col + row] = true;
                backslash[row-col + n] = true;
                usedRow[row] = true;
            }
        }
    }

    int totalNQueens(int n) {
        vector<bool> slash(n*2,true);
        vector<bool> backslash(n*2,true);
        vector<bool> usedRow(n,true);
        
        int ret = 0;
        queens(ret,slash,backslash,usedRow,0,n);
        return ret;
    }
};
Solution #2
http://www.matrix67.com/blog/archives/266  

Update on Nov-13-2014 
基本思路为DFS
~(row | slash | backSlash) 代表每行上的可放位置,当切入到下一行时,slash跟backSlash分别需要位移一位
possiblePosition 代表当前行所有可放入棋子的位置
rightMostOne 代表当前放入棋子的位置
拿一个例子走一遍代码,立即能明白此算法
class Solution {
public:
    void bitOP(int &num, int row, int slash, int backSlash, int n) {
        int upperLimit = (1 << n) - 1; // upperLimit has n of '1'
        if (row == upperLimit) {
            num++;
            return;
        }
        
        int possiblePosition = upperLimit & (~(row | slash | backSlash)); // get posiible positions for queen in a row
        while (possiblePosition != 0) {
            int rightMostOne = possiblePosition & (-possiblePosition); // get the most right '1' as new queen's position
            possiblePosition -= rightMostOne;
            bitOP(num, row + rightMostOne, (slash + rightMostOne) << 1, (backSlash + rightMostOne) >> 1,n);
        }
        
    }

    int totalNQueens(int n) {
        int num = 0;
        bitOP(num,0,0,0,n);
        return num;
    }
};
Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
-----------------------------------------------------------
Similar to #59, Spiral Matrix II
start at the outer most layer
class Solution {
public:
    void spiral (vector<vector<int> > &matrix, vector<int> &ret, int m, int n, int k) {
        if (m <= 0 || n <= 0) {
            return;
        }
        
        if (m == 1) {
            for (int i = 0; i < n; i++) {
                ret.push_back(matrix[k][k + i]);
            }
            return;
        }
        
        if (n == 1) {
            for (int i = 0; i < m; i++) {
                ret.push_back(matrix[k + i][k]);
            }
            return;
        }
        
        // going right
        for (int i = 0; i < n - 1; i++) {
            ret.push_back(matrix[k][i + k]);    
        }
        
        // going down
        for (int i = 0; i < m - 1; i++) {
            ret.push_back(matrix[k + i][n - 1 + k]);
        }
        
        // going left
        for (int i = 0; i < n - 1; i++ ) {
            ret.push_back(matrix[m - 1 + k][n - 1 + k - i]);
        }
        
        // going up
        for (int i = 0; i < m - 1; i++ ) {
            ret.push_back(matrix[k + m - 1 - i][k]);
        }
        
        spiral(matrix,ret,m-2,n-2,k+1);
    }

    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        int m = matrix.size();
        vector<int> ret;
        if (m == 0) return ret;
        int n = matrix[0].size();
        spiral(matrix,ret,m,n,0);
        return ret;
    }
};