问题:如果求一个数列的最长递增子序列?
1.下面是一段有bug的代码,输出的结果也是错的,以后作为反面教材,时常复习!
package 最长递增子序列;
public class 叠罗汉1 {
public int getHeight(int[] men, int n) {
// write code here
if (n == 0) {
return 0;
}
int[] dp = new int[n];
dp[0] = 1;
for (int i = 1; i < n; i++) {
boolean flag = true;
for (int j = i - 1; j >= 0; j--) {
if (men[i] > men[j]) {
dp[i] = dp[j] + 1;
flag = false;
break;//不可以直接break掉,如果举个反例就是 :4 5 6 3 8序列
}
}
if(flag){
dp[i] =1;
}//没必要设置flag,有更加优雅的方式
}
int res = Integer.MIN_VALUE;
for(int i =0;i<n;i++){
if(dp[i] > res){
res = dp[i];
}
}
return res;
}
public static void main(String[] args) {
//int[] men = {1092087,253439,1229092,2638575,2592914,1545673,2357912,1464954,1482904,2115048,1039606,3019682,2499687,2603974,235944,2029011,2594318,26817,2530237,2653234,1518368,102504,751515,1273453,252197,2328429,114699,833494,2437962,1897327,2358947,728206,1694538,1111877,2304261,1550585,2795216,1128077,2526780,2408154,1675787,1569084,542965,864374,2005718,2162685,562828,1806478,489256,643066,2684533,2308573,1242746,663914,893865,1350619,920645,706738,2053610,2975455,803894,37303,108282,78804,97230,2172571,1461268,2662562,597858,1434826,1379291,2481759,671296,489579,1997678,1361658,1793206,2500057,2428656,2228999,2758410,1766219,119904,2336578,1806119,1552636,1475687,1859500,773279,882156,286334,2887969,1579820,2178007,1736233,2042787,1545966,1657224,2524335,477841,256167,973209,2432626,564747,1915507,933567,2478598};
int[] men = {3,2,1,4,5,0};
int n = men.length;
System.out.println(new 叠罗汉1().getHeight(men, n));
}
}
2.改进版的代码
package 最长递增子序列;
public class 叠罗汉1 {
public int getHeight(int[] men, int n) {
// write code here
if (n == 0) {
return 0;
}
int[] dp = new int[n];
dp[0] = 1;
for (int i = 1; i < n; i++) {
dp[i]=1;
for (int j = i - 1; j >= 0; j--) {
if (men[i] > men[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
int res = Integer.MIN_VALUE;
for(int i =0;i<n;i++){
if(dp[i] > res){
res = dp[i];
}
}
return res;
}
public static void main(String[] args) {
int[] men = {1092087,253439,1229092,2638575,2592914,1545673,2357912,1464954,1482904,2115048,1039606,3019682,2499687,2603974,235944,2029011,2594318,26817,2530237,2653234,1518368,102504,751515,1273453,252197,2328429,114699,833494,2437962,1897327,2358947,728206,1694538,1111877,2304261,1550585,2795216,1128077,2526780,2408154,1675787,1569084,542965,864374,2005718,2162685,562828,1806478,489256,643066,2684533,2308573,1242746,663914,893865,1350619,920645,706738,2053610,2975455,803894,37303,108282,78804,97230,2172571,1461268,2662562,597858,1434826,1379291,2481759,671296,489579,1997678,1361658,1793206,2500057,2428656,2228999,2758410,1766219,119904,2336578,1806119,1552636,1475687,1859500,773279,882156,286334,2887969,1579820,2178007,1736233,2042787,1545966,1657224,2524335,477841,256167,973209,2432626,564747,1915507,933567,2478598};
//int[] men = {3,2,1,4,5,0};
int n = men.length;
System.out.println(new 叠罗汉1().getHeight(men, n));
}
}