原创 Longest Valid Parentheses

DP題,過程如下:計算出以每一個元素結尾所能形成的最長合法括號子串,其中最大值即爲所求。時間複雜度,空間複雜度都是O(n)。 記當前位置下標爲 i : 1,若 i 位置爲 ' ( ' ,則dp[i] = 0; 2,若 i 位置爲 ' )

原创 Sort Colors

題意是: 對只含0,1,2三個元素的數組進行排序。由於只含3個元素,O(nlogn)肯定不是一個好的算法。 1,首先能想到的是計數排序,時間複雜度O(n), 空間複雜度O(1): public class Solution { p

原创 Median of Two Sorted Arrays

解析在這裏:http://blog.csdn.net/mazhichao300/article/details/9714291  稍有不同,解析處是針對於求中間元素。而本題可以求第K個元素。   class Solution { publ

原创 The Dominant Color

http://pat.zju.edu.cn/contests/pat-a-practise/1054 求數組中出現次數超過一半的那個數字(題目保證一定存在)。 解法一:用哈希表。這裏就不給出代碼了。 解法二:有一個數字出現次數超過了一半

原创 Subsets

先對S進行排序, 之後深搜, 每個數字有選或不選兩種情況。 class Solution { public: vector<vector<int> > ans; void cal(vector<int> s, vector<i

原创 Best Time to Buy and Sell Stock

對於第i個節點, 計算出從 0 - i的最小值, 從i + 1  -  n 的最大值。 public class Solution { public int maxProfit(int[] prices) { /

原创 Trapping Rain Water

class Solution { public: int trap(int A[], int n) { // Start typing your C/C++ solution below // D

原创 Best Time to Buy and Sell Stock II

貪心算法,有利可圖即買入,賣出。 class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ s