lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  1846 随笔 :: 0 文章 :: 109 评论 :: 288万 阅读

1. 题目

读题

HJ103 Redraiment的走法

 

 

考查点

 

2. 解法

思路

 

代码逻辑

 

具体实现

import java.util.Arrays;

// 动态规划求最长递增子序列长度
public class Solution {
    public int longestIncreasingSubsequence(int[] nums) {
        // 数组为空,返回0
        if (nums == null || nums.length == 0) return 0;
        // 数组长度
        int n = nums.length;
        // dp数组,存储每个元素结尾的最长递增子序列长度
        int[] dp = new int[n];
        // 最长递增子序列长度
        int ans = 1;
        // 把dp数组的所有元素都设为1
        Arrays.fill(dp, 1);
        // 从左到右遍历原数组
        for (int i = 0; i < n; i++) {
            // 从左到右遍历i之前的所有元素
            for (int j = 0; j < i; j++) {
                // 如果nums[j] < nums[i],更新dp[i]
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            // 更新ans
            ans = Math.max(ans, dp[i]);
        }
        // 返回ans
        return ans;
    }

    // 测试
    public static void main(String[] args) {
        // 示例数组
        int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
        // 创建对象
        Solution solution = new Solution();
        // 调用函数
        int ans = solution.longestIncreasingSubsequence(nums);
        // 输出结果
        System.out.println("The length of the longest increasing subsequence is: " + ans);
    }
}

自行实现

public class HJ103 {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
System.out.println(longestSeq(nums));
sc.close();
}

public static int longestSeq(int[] nums) {

int n = nums.length;
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
}

int max = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
max = Math.max(dp[i], max);

}
}
}

return max;

}
}

3. 总结

posted on   白露~  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2022-07-28 leetcode-1853. 转换日期格式
2022-07-28 leetcode-1211. 查询结果的质量和占比
2021-07-28 CC邮件抄送文化
2019-07-28 shoshana-摄影文集
2019-07-28 shoshana-技术文集
点击右上角即可分享
微信分享提示