Java Backtracking with HashSet


  • 0
    M
        public boolean canWin(String s) {
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i + 1< s.length(); i ++) {
                if (s.charAt(i) == s.charAt(i + 1) && s.charAt(i) == '+') {
                    set.add(i);
                }
            }
            
            return helper(set);
        }
        
        public boolean helper(Set<Integer> set) {
            for (int move : set) {
                
                Set<Integer> newSet = new HashSet<>(set);
                newSet.remove(move);
                boolean hasLeft = newSet.remove(move - 1);
                boolean hasRight = newSet.remove(move + 1);
                if (!helper(newSet)) {
                    return true;
                }
                
                newSet.add(move);
                if (hasLeft) newSet.add(move - 1);
                if (hasRight) newSet.add(move + 1);
            }
            return false;
        }

Log in to reply
 

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