Can anyone explain to me why this backtracking solution is not correct?


  • 0
    X

    public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
    int start=0;
    boolean res=false;
    helper(start, s, wordDict, res);
    return res;
    }

    public void helper(int start, String s, List<String>wordDict, boolean res){
        if(start>=s.length()) {
            res=true;
            System.out.println("this is true");
            return;
        }
        for(int i=start;i<s.length();i++){
            String substr=s.substring(start,i+1);
            if(wordDict.contains(substr)){
                int newStart=i+1;
                helper(newStart, s, wordDict, res);
            }
        }
    }   
    

    }

    I have test the code and the
    if(start>=s.length()) {
    res=true;
    System.out.println("this is true");
    return;
    }
    has been excuted. But why the sample test case still return false?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.