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 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误