Idea: recursive solution of enumeration Split points, which can be optimized by DP.
Pay attention to recursive termination conditions.
Note ^ & | there are three different statistical conditions.
import java.util.HashMap;import java.util.Map;public class Solution { int countR(String terms, boolean result, int start, int end, Map<String, Integer> cache) { String key = "" + result + start + end; if (cache.containsKey(key)) { return cache.get(key); } if (start == end) { if (terms.charAt(start) == ‘0‘) { if (result) return 0; else return 1; } else { if (result) return 1; else return 0; } } int count = 0; if (result) { for (int i = start + 1; i < end; i++) { char op = terms.charAt(i); if (op == ‘&‘) { count += countR(terms, true, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); } else if (op == ‘|‘) { count += countR(terms, true, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); count += countR(terms, true, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); count += countR(terms, false, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); } else if (op == ‘^‘) { count += countR(terms, true, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); count += countR(terms, false, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); } } } else { for (int i = start + 1; i < end; i++) { char op = terms.charAt(i); if (op == ‘&‘) { count += countR(terms, true, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); count += countR(terms, false, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); count += countR(terms, false, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); } else if (op == ‘|‘) { count += countR(terms, false, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); } else if (op == ‘^‘) { count += countR(terms, true, start, i - 1, cache) * countR(terms, true, i + 1, end, cache); count += countR(terms, false, start, i - 1, cache) * countR(terms, false, i + 1, end, cache); } } } cache.put(key, count); return count; } public static void main(String[] args) { String terms = "0^0|1&1^1|0|1"; boolean result = true; Map<String, Integer> cache = new HashMap<String, Integer>(); System.out.println(new Solution().countR(terms, result, 0, terms.length() - 1, cache)); }}
9.11 given a Boolean expression, it consists of 0, 1, &, |, ^, and other symbols, as well as a desired boolean result to implement a function, this expression can be used to obtain the result value by calculating the placement of several parentheses.