q294402756 2015-07-20 15:48 采纳率: 50%
浏览 1787

动态规划初始化问题,类似于下面这道题leetcode:Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that "rgeat" is a scrambled string of "great".
Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string"rgtae".
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
We say that "rgtae" is a scrambled string of "great".
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

  public class Solution {
    /**
     * @param s1 A string
     * @param s2 Another string
     * @return whether s2 is a scrambled string of s1
     */
    public boolean isScramble(String s1, String s2) {
        // Write your code here
        int n = s1.length();
        if (s2.length() != n) 
            return false;

        boolean dp[][][] = new boolean[n][n][n];

        // case: length is 1
        for (int i=0; i<n; i++)
            for (int j=0; j<n; j++)
                dp[i][j][0] = s1.charAt(i) == s2.charAt(j);


        // case: length is 2....n
        for (int l=1; l<n; l++)
        {
            for (int i=0; i+l<n; i++)
            {
                for (int j=0; j+l<n; j++)
                {
                    for (int k=0; k<l; k++)
                    {
                        if ((dp[i][j][k] && dp[i+k+1][j+k+1][l-1-k])   
                         || (dp[i][j+l-k][k] && dp[i+k+1][j][l-1-k]))
                            dp[i][j][l] = true;
                    }
                }
            }
        }

        return dp[0][0][n-1];
    }

}

代码中对dp[i][j][0]初始化定义 一般这种动态规划的题目都有初始定义。这种初始定义有什么意义?这道题中的初始化代码有什么意义?一般动态规划的题目怎么确定该如何初始化?求大神来解惑一下,不甚感谢

  • 写回答

1条回答

  • threenewbee 2015-07-20 22:15
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝