动态规划-Minimum Distance to Type a Word Using Two Fingers

2020-01-12 18:28:13

问题描述

问题求解

本题还是非常困难的,至少我在看到这个题目的时候是没有想到怎么解决的。我当时联想到的题目是那条grid走两遍的题目,那条题目也很麻烦,使用的是dp。

本题最终的解决方式其实是和那条题目是类似的,也是使用dp的方式去做。

最大的类似在于,这两题都可以使用dfs + me来进行解决,dfs和dp任何一个都是解决问题的大杀器,他们的结合就更是非常的厉害。很多的题目直接使用自底向上的dp是不容易写的,但是结合dfs使用me的dp则非常的直观并且效率依然很高。

这两条题目都是采用的这个算法,结构清晰且逻辑严明,本质上都是解空间的遍历,但是利用了dp的思路将其中的一些解保存了下来方便了后续的计算。

    int[][][] dp = new int[27][27][301];
    
    public int minimumDistance(String word) {
        return helper(word, 0, 0, 0);
    }
    
    private int helper(String word, int start, int l, int r) {
        if (start >= word.length()) return 0;
        if (dp[l][r][start] != 0) return dp[l][r][start];
        int idx = word.charAt(start) - 'A' + 1;
        dp[l][r][start] = Math.min(dist(l, idx) + helper(word, start + 1, idx, r), dist(r, idx) + helper(word, start + 1, l, idx));
        return dp[l][r][start];
    }
    
    private int dist(int from, int to) {
        if (from == 0) return 0;
        int x1 = (from - 1) / 6;
        int y1 = (from - 1) % 6;
        int x2 = (to - 1) / 6;
        int y2 = (to - 1) % 6;
        return Math.abs(x1 - x2) + Math.abs(y1 - y2);
    }

  

猜你喜欢

转载自www.cnblogs.com/hyserendipity/p/12183423.html