因为最近一段时间接触了一些Leetcode上的题目,发现许多题目的解题思路相似,从中其实可以了解某类算法的一些应用场景. 这个随笔系列就是我尝试的分析总结,希望也能给大家一些启发. 动态规划的基本概念 一言以蔽之,动态规划就是将大问题分成小问题,以迭代的方式求解. 可以使用动态规划求解的问题一般有如下的两个特征: 1.有最优子结构(optimal substructure) 即待解决问题的最优解能够通过求解子问题的最优解得到. 2.子问题间有重叠(overlapping subproplems)…
问题描述: 在股市的交易日中,假设最多可进行两次买卖(即买和卖的次数均小于等于2),规则是必须一笔成交后进行另一笔(即买-卖-买-卖的顺序进行).给出一天中的股票变化序列,请写一个程序计算一天可以获得的最大收益.请采用实践复杂度低的方法实现. 给定价格序列prices及它的长度n,请返回最大收益.保证长度小于等于500. class Solution { public: int maxProfit(vector<int>& prices) { //It's wrong if you c…
Question: Find the contiguous subarray within an array (containing at least one number) that has the largest sum. For example, given the array [2, 1, –3, 4, –1, 2, 1, –5, 4], The contiguous array [4, –1, 2, 1] has the largest sum = 6. 此问题提供了两种解决方案,首先…
Leetcode里面关于字符串的一些问题,描述如下: Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the". Update (2015-02-12):For C programmers: Try to solve it inO(1) space. click to show cla…
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1.…
Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => true"abc" => false"1 a" => false"2e10" => true 解决方案: public class Solution { public boolean isNumber(String s) { in…
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 注:直接看题目可能会有些偏差,因为容易认为 needle是一个字符,那就也太容易了,实则,haystack和needle都是字符串(注意是字符串不是数组) 解法思路: 暴力搜索: public class Solution { public int…
Question: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome.Example Questions C…
class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { vector<pair<int, int> > h, res; multiset<int> m; , cur = ; for (auto &a : buildings) { h.push_back({a[], -a[]});…
dp动态规划分类详解 转自:http://blog.csdn.NET/cc_again/article/details/25866971 动态规划一直是ACM竞赛中的重点,同时又是难点,因为该算法时间效率高,代码量少,多元性强,主要考察思维能力.建模抽象能力.灵活度. ****************************************************************************************** 动态规划(英语:Dynamic programm…