打家劫舍
题目描述:用一个数组表一排房屋中的金钱数量,强盗想要抢到最多的金钱,但是唯一的限制是不能抢相邻的房子,求强盗能抢到的最大数额:
用dp数组记录截至到第n间房最多可以抢到多少钱
public int rob(int[] nums) {
int len = nums.length;
if(len == 0)return 0;
if(len == 1)return nums[0];
int[] temp = new int[len]; //temp[n]表示在n及之前房屋中能抢到最多的钱
temp[0] = nums[0];
temp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < len; i++) {
temp[i] = Math.max(nums[i] + temp[i - 2], temp[i - 1]);
}
return Math.max(temp[len-1], temp[len-2]);
}
最长上升序列:
如[10,9,2,5,3,7,101,18],最长上升子序列是[2,3,7,101],输出最长上升序列长度;
用一个dp数组保存最长上升子序列长度,如dp[i]表示前i个数中最长上升子序列长度,dp[i+1]至多比dp[i]增大1
public int lengthOfLIS(int[] nums) {
if(nums.length == 0) return 0;
int result = 1;
int[] dp = new int[nums.length];
dp[0] = 1;
for(int i = 1;i<nums.length;i++) {
int max = 0;
for(int j = 0;j<i;j++) {
if(nums[j] < nums[i]){
max = Math.max(max,dp[j]);
}
}
dp[i] = max+1;
result = Math.max(result,dp[i]);
}
return result;
}
最长公共子序列:
求两个字符串的最长公共子序列的长度,如"abcd"和"bced"的最长公共子序列为"bcd",长度为3;
创建一个二维数组dp[][]记录局部最长公共子序列长度,例如dp[2][1]表示"abc"和"bc"的最长公共子序列
public int longestCommonSubsequence(String text1, String text2) {
int l1 = text1.length();
int l2 = text2.length();
int[][] dp = new int[l1+1][l2+1];
for(int i = 1;i<=l1;i++){
for(int j = 1;j<=l2;j++){
if(text1.charAt(i-1) == text2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+1;
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[l1][l2];
}
来源:CSDN
作者:weixin_43724742
链接:https://blog.csdn.net/weixin_43724742/article/details/103788568