Word Break III

http://www.lintcode.com/en/problem/word-break-iii/

import java.util.Set;

public class Solution {
    private int res = 0;

    /*
     * @param : A string
     * @param : A set of word
     * @return: the number of possible sentences.
     */
    public int wordBreak3(String s, Set dict) {
        // Write your code here
//        暴力穷举,比2更简单
        tree(s, dict, 0, s.length());
        return res;
    }

    private void tree(String s, Set dict, int l, int r) {
        if (l == r) {
            res++;
            return;
        }
        for (int i = l; i < r; i++) {
            String pre = s.substring(l, i + 1);
            if (dict.contains(pre)) {
                tree(s, dict, i + 1, r);
            }
        }
    }
}

你可能感兴趣的:(Word Break III)