[leetcode] 题型整理之动态规划
动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助
55. Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
不停扩展最远序号
代码较短,直接贴代码吧
public class Solution {
public boolean canJump(int[] nums) {
int length = nums.length;
if (nums == null || length == 0) {
return false;
}
int farthest = nums[0];
for (int i = 0; i < length; i++) {
if (i > farthest) {
return false;
}
int x = i + nums[i];
if (x > farthest) {
farthest = x;
}
if (farthest >= length - 1) {
return true;
}
}
return farthest >= length - 1;
}
}
53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
代码当中,通过使用prev变量减少读取读取内存的次数。
public class Solution {
public int maxSubArray(int[] nums) {
int length = nums.length;
if (length == 0) {
return 0;
}
int[] rr = new int[length];
rr[0] = nums[0];
int result = nums[0];
int prev = result;
for (int i = 1; i < length; i++) {
int x = prev > 0 ? prev : 0;
prev = x + nums[i];
rr[i] = prev;
if (result < prev) {
result = prev;
}
}
return result;
}
}
63. Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
从右下方向左上方获得各个位置到终点的路径数量。
public class Solution {
int m;
int n;
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
m = obstacleGrid.length;
if (m == 0) {
return 0;
}
n = obstacleGrid[0].length;
if (n == 0) {
return 0;
}
int[][] paths = new int[m][n];
int mMinus = m - 1;
int nMinus = n - 1;
int x = paths[0][0];
if (x == 1) {
return 0;
}
x = obstacleGrid[mMinus][nMinus];
if (x == 1) {
return 0;
} else {
paths[mMinus][nMinus] = 1;
}
for (int i = n - 2; i >= 0; i--) {
paths[mMinus][i] = obstacleGrid[mMinus][i] == 1 ? 0 : paths[mMinus][i + 1];
}
for (int i = m - 2; i >= 0; i--) {
paths[i][nMinus] = obstacleGrid[i][nMinus] == 1 ? 0 : paths[i + 1][nMinus];
}
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
if (obstacleGrid[i][j] == 1) {
paths[i][j] = 0;
} else {
paths[i][j] = paths[i + 1][j] + paths[i][j + 1];
}
}
}
return paths[0][0];
}
}
91. Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
public class Solution {
public int numDecodings(String s) {
int length = s.length();
if (length == 0) {
return 0;
}
int[] result = new int[length];
if (s.charAt(0) == '0') {
result[0] = 0;
} else {
result[0] = 1;
}
if (length == 1) {
return result[0];
}
String string = s.substring(0, 2);
int x = Integer.valueOf(string);
if (s.charAt(1) == '0') {
result[1] = 0;
if (x <= 26 && x >= 10) {
result[1]++;
}
} else {
result[1] = result[0];
if (x <= 26 && x >= 10) {
result[1]++;
}
}
for (int i = 2; i < length; i++) {
char char0 = s.charAt(i);
int r = 0;
if (char0 != '0') {
r += result[i - 1];
}
string = s.substring(i - 1, i + 1);
x = Integer.valueOf(string);
if (x <= 26 && x >= 10) {
r += result[i - 2];
}
result[i] = r;
}
return result[length - 1];
}
}
139. Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
s = " "+s;
int l = s.length();
boolean[] p = new boolean[l];
p[0] = true;
for(int i = 1; i < l; i++){
for(int j = 0; j < i; j++){
if(p[j] && wordDict.contains(s.substring(j+1,i+1))){
p[i] = true;
break;
}
}
}
if(p[l - 1]){
return true;
}
else{
return false;
}
}
}
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
256. Paint House
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.
public class Solution {
public int minCost(int[][] costs) {
int length = costs.length;
if (length == 0) {
return 0;
}
int[][] r = new int[length][3];
r[0][0] = costs[0][0];
r[0][1] = costs[0][1];
r[0][2] = costs[0][2];
int a0, a1, a2;
for (int i = 1; i < length; i++) {
a0 = r[i - 1][0];
a1 = r[i - 1][1];
a2 = r[i - 1][2];
r[i][0] = Math.min(a1, a2) + costs[i][0];
r[i][1] = Math.min(a0, a2) + costs[i][1];
r[i][2] = Math.min(a0, a1) + costs[i][2];
}
int lengthMinus = length - 1;
int x1 = r[lengthMinus][0];
int x2 = r[lengthMinus][1];
int x3 = r[lengthMinus][2];
return x1 < x2 ? Math.min(x1, x3) : Math.min(x2, x3);
}
}
309. Best Time to Buy and Sell Stock with Cooldown
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
public class Solution {
public int maxProfit(int[] prices) {
final int length = prices.length;
if (length < 2) {
return 0;
}
int[] buys = new int[length];
int[] sells = new int[length];
buys[0] = 0 - prices[0];
buys[1] = Math.max(-prices[0], -prices[1]);
sells[0] = 0;
sells[1] = Math.max(0, prices[1] - prices[0]);
for (int i = 2; i < length; i++) {
buys[i] = Math.max(buys[i - 1], sells[i - 2] - prices[i]);
sells[i] = Math.max(sells[i - 1], buys[i - 1] + prices[i]);
}
return sells[length - 1];
}
}
325. Maximum Size Subarray Sum Equals k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
public class Solution {
public int maxSubArrayLen(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = nums.length;
int sum = 0;
int result = 0;
map.put(0, -1);
for (int i = 0; i < length; i++) {
sum += nums[i];
if (!map.containsKey(sum)) {
map.put(sum, i);
}
Integer r = map.get(sum - k);
if (r != null) {
result = Math.max(result, i - r);
}
}
return result;
}
}
377. Combination Sum IV
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4 The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
public class Solution {
public int combinationSum4(int[] nums, int target) {
int[] rr = new int[target + 1];
Arrays.fill(rr, 0);
rr[0] = 1;
Arrays.sort(nums);
int length = nums.length;
for (int i = 1; i <= target; i++) {
for (int j = 0; j < length; j++) {
int x = nums[j];
int tt = i - x;
if (tt < 0) {
break;
}
int prev = rr[tt];
rr[i] += prev;
}
}
return rr[target];
}
}
[leetcode] 题型整理之动态规划的更多相关文章
- [leetcode] 题型整理之二叉树
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' va ...
- [leetcode] 题型整理之排列组合
一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...
- [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余
需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...
- [leetcode] 题型整理之cycle
找到环的起点. 一快一慢相遇初,从头再走再相逢.
- [leetcode]题型整理之用bit统计个数
137. Single Number II Given an array of integers, every element appears three times except for one. ...
- [leetcode] 题型整理之图论
图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦. 求最短路径: 127. Word Ladder Given two words (beginWord and end ...
- [leetcode] 题型整理之查找
1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...
- [leetcode] 题型整理之排序
75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...
- [leetcode] 题型整理之字符串处理
71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example,path = &q ...
随机推荐
- Java 虚拟机
Java 虚拟机工作原理详解 一.类加载器 首先来看一下 java 程序的执行过程. 从这个框图很容易大体上了解 java 程序工作原理.首先,你写好 java 代码,保存到硬盘当中.然后你在命令行中 ...
- <<< 数据库基础知识
相关概念: 1.数据 (DATA) : 数据是描述现实世界事物的符号标记, 是指用物理符号记录下来的可以鉴别的信息. 包括:数字.文字.图形.声音.及其他特殊符号 2.数据库(DATABASE) :按 ...
- oracle---日期等plsql
日期/时间 相关查询 1.获取当前月份的第一天 运行这个命令能快速返回当前月份的第一天.你可以用任何的日期值替换 "SYSDATE"来指定查询的日期. SELECT TRUNC ( ...
- Web jquery表格组件 JQGrid 的使用 - 7.查询数据、编辑数据、删除数据
系列索引 Web jquery表格组件 JQGrid 的使用 - 从入门到精通 开篇及索引 Web jquery表格组件 JQGrid 的使用 - 4.JQGrid参数.ColModel API.事件 ...
- 20145204&20145212信息安全系统实验一报告
信息安全系统实验报告 实验一 步骤 1.连接 arm 开发板 将 arm 开发板的电源线接好,使得开发板开关处于闭合状态.再分别将串口线.并口线和网线与 pc 机连接好. 2.建立超级终端 运行 wi ...
- 即时搜索或input实时检测监听输入框变化
js实现的文本框内容发生改变立马触发事件简单介绍:本章节介绍一下如何在文本框的内容发生变化的时候,立马触发一个事件执行响应的操作,而不是像是keydow或者keyup事件一样,只能够检测通过键盘输入导 ...
- golang笔记——array
1.定义一个 array 数组长度也是类型的一部分,比如长度为3的int数组与长度为5的int数组,并不是同一类型. package main import ( "strconv" ...
- [译]ES6中的代理对象
原文:http://ariya.ofilabs.com/2013/07/es6-and-proxy.html 能够拦截在一个对象上的指定操作的能力是非常有用的,尤其是在故障调试的时候.通过ECMASc ...
- 【转载】使用Pandas对数据进行筛选和排序
使用Pandas对数据进行筛选和排序 本文转载自:蓝鲸的网站分析笔记 原文链接:使用Pandas对数据进行筛选和排序 目录: sort() 对单列数据进行排序 对多列数据进行排序 获取金额最小前10项 ...
- 自动化运维工具Ansible详细部署 (转载)
自动化运维工具Ansible详细部署 标签:ansible 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://sofar.blog. ...