Leetcode1218 最长定差子序列 哈希表优化DP

  一道中规中矩的 DP 题目,但因为问题空间较大,需要做一些优化。

  分治法:

int an = 0;

    public final int longestSubsequence(int[] arr, int difference) {
        if (arr.length == 0) {
            return 0;
        }
        longestSubsequence(arr, difference, 0, new int[arr.length]);
        return an + 1;
    }

    /**
     * @Author Niuxy
     * @Date 2020/7/15 9:47 上午
     * @Description G(point) 表示以 arr[point] 为头元素的最长定差子序列的长度
     */
    public final int longestSubsequence(int[] arr, int difference, int point, int[] cache) {
        if (point == arr.length - 1) {
            return 0;
        }
        if (cache[point] != 0) {
            return cache[point];
        }
        int an = 0;
        for (int i = point + 1; i < arr.length; i++) {
            int currentDiff = arr[i] - arr[point];
            int next = longestSubsequence(arr, difference, i, cache);
            if (currentDiff != difference) {
                continue;
            }
            an = Math.max(an, 1 + next);
        }
        cache[point] = an;
        this.an = Math.max(an, this.an);
        return an;
    }

  转为 DP :

public final int longestSubsequenceDP0(int[] arr, int difference) {
        if (arr.length == 0) {
            return 0;
        }
        int[] dp = new int[arr.length];
        int an = 0;
        for (int i = arr.length - 2; i >= 0; i--) {
            int temp = 0;
            for (int j = i + 1; j < arr.length; j++) {
                int currentDiff = arr[j] - arr[i];
                if (currentDiff != difference) {
                    continue;
                }
                temp = Math.max(temp, dp[j] + 1);
            }
            dp[i] = temp;
            an = Math.max(an, temp);
        }
        return an+1;
    }

  分治转为 DP 后依然超时,要么需要重新定义状态转移方程,要么需要剪枝。

  内部的 for 循环是为了寻找定差的下一个元素,其实有了基准值和差值,完全可以通过哈希表替代循环。使用哈希表优化:

    public final int longestSubsequenceDP1(int[] arr, int difference) {
        Map<Integer, Integer> dp = new HashMap<Integer, Integer>();
        dp.put(arr[arr.length-1],1);
        int an = 0;
        for (int i = arr.length - 2; i >= 0; i--) {
            int pre = 1;
            int key=arr[i]+difference;
            if(dp.containsKey(key)){pre=dp.get(key)+1;}
            dp.put(arr[i], pre);
            an = Math.max(an, pre);
        }
        return an;
    }

 

posted @ 2020-07-15 14:22  牛有肉  阅读(193)  评论(0编辑  收藏  举报