遞歸&動態規劃-解碼方法

一條包含字母 A-Z 的消息通過以下方式進行了編碼:

‘A’ -> 1
‘B’ -> 2

‘Z’ -> 26
給定一個只包含數字的非空字符串,請計算解碼方法的總數。

leetcode

遞歸

    public int numDecodings(String s) {
        int total = 0;
        if (s.isEmpty()) {
            return total;
        }
        
        String first = s.substring(0, 1);
        if (0==Integer.valueOf(first)) {
            return 0;
        }
        
        if (s.length() == 1) {
            return 1;
        }
        
        int n = numDecodings(s.substring(1));
        if (n>0) {
            total += n;
        } 
        
        first = s.substring(0, 2);
        int x = Integer.valueOf(first);
        if (x<=26) {
            String y = s.substring(2);
            if (y.isEmpty()) {
                total += 1;
            } else {
                int t = numDecodings(y);
                if (t>0) {
                    total += t;
                }
            }
        }
        
        return total;
    }

動態規劃

   public int numDecodings(String s) {
       if (s.isEmpty() || s.startsWith("0")) {
            return 0;
        }

        int[] memo = new int[s.length()];
        memo[0]=1;

        if (s.length() > 1) {
            Integer x = Integer.valueOf(s.substring(0,2));
            if (s.charAt(1) == '0') {
                if (x<27) {
                    memo[1] = 1;
                } else {
                    memo[1] = 0;
                }

            } else {
                if (x<27) {
                    memo[1] = 2;
                } else {
                    memo[1] = 1;
                }
            }
        }

        for(int i=2;i<s.length();++i) {

            String x = s.substring(i, i+1);
            String y = s.substring(i-1, i+1);
            if (x.equals("0")) {
                if (y.equals("00")) {
                    memo[i]=0;
                } else {
                    int k = Integer.valueOf(y);
                    if (k<27) {
                        memo[i] = memo[i-2];
                    } else {
                        memo[i]=0;
                    }
                }
            } else {
                memo[i] = memo[i-1];
                if(!y.startsWith("0")){
                    int k = Integer.valueOf(y);
                    if (k<27) {
                        memo[i] += memo[i-2];
                    }
                }
            }
        }

        return memo[s.length()-1];
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章