Skip to content

Commit ceed111

Browse files
author
chenweijie
committed
dp-3
1 parent 6fffcdd commit ceed111

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.chen.algorithm.znn.dynamic.test300;
2+
3+
import org.junit.Test;
4+
5+
import java.util.Arrays;
6+
7+
/**
8+
* https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/
9+
*
10+
* @Auther: zhunn
11+
* @Date: 2020/11/4 21:03
12+
* @Description: 最长上升子序列:1-动态规划;2-动态规划-优化空间(贪心+二分查找)
13+
*/
14+
public class Solution {
15+
16+
public int lengthOfLIS(int[] nums) {
17+
if (nums == null || nums.length == 0) {
18+
return 0;
19+
}
20+
21+
int len = nums.length;
22+
int[] dp = new int[len];
23+
Arrays.fill(dp, 1);
24+
25+
int res = 0;
26+
for (int i = 1; i < len; i++) {
27+
for (int j = 0; j < i; j++) {
28+
if (nums[j] < nums[i]) {
29+
dp[i] = Math.max(dp[i], dp[j] + 1);
30+
}
31+
}
32+
res = Math.max(res, dp[i]);
33+
}
34+
35+
return res;
36+
}
37+
38+
@Test
39+
public void test() {
40+
int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
41+
System.out.println(lengthOfLIS(nums));
42+
}
43+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.chen.algorithm.znn.dynamic.test322;
2+
3+
import org.junit.Test;
4+
5+
import java.util.Arrays;
6+
7+
8+
/**
9+
* https://leetcode-cn.com/problems/coin-change/solution/dong-tai-gui-hua-shi-yong-wan-quan-bei-bao-wen-ti-/
10+
* 官方解答:https://leetcode-cn.com/problems/coin-change/solution/322-ling-qian-dui-huan-by-leetcode-solution/
11+
*
12+
* @Auther: zhunn
13+
* @Date: 2020/11/4 22:03
14+
* @Description: 零钱兑换:1-动态规划;2-动态规划-优化空间
15+
*/
16+
public class Solution {
17+
18+
public int coinChange(int[] coins, int amount) {
19+
if (coins == null || coins.length == 0) {
20+
return -1;
21+
}
22+
23+
int max = amount + 1;
24+
int[] dp = new int[amount + 1]; // 给 0 占位
25+
Arrays.fill(dp, max); // 注意:因为要比较的是最小值,这个不可能的值就得赋值成为一个最大值
26+
27+
dp[0] = 0; // 理解 dp[0] = 0 的合理性,单独一枚硬币如果能够凑出面值,符合最优子结构
28+
for (int i = 1; i <= amount; i++) {
29+
for (int j = 0; j < coins.length; j++) {
30+
if (coins[j] <= i) {
31+
dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
32+
}
33+
}
34+
}
35+
return dp[amount] > amount ? -1 : dp[amount];
36+
}
37+
38+
@Test
39+
public void test() {
40+
int[] nums = {1, 2, 5};
41+
int amount = 10;
42+
System.out.println(coinChange(nums, amount));
43+
}
44+
}

0 commit comments

Comments
 (0)