2767. 将字符串分割为最少的美丽子字符串
Java:
class Solution {int cnt;int ans;int[] arr;Set<Integer> set;private void dfs(String s, String s1, int pos, int len) {if (pos == len) {ans = Math.min(ans, cnt);return;}for(int i = pos; i < len; ++i) {String s2 = s.substring(pos, i + 1);int num = Integer.parseInt(s2, 2);if (!s2.startsWith("0") && set.contains(num)) { //"101101111101" 防止 01111101,题意要求全部分隔++cnt;dfs(s, s2, i + 1, len);--cnt;}}}public int minimumBeautifulSubstrings(String s) {cnt = 0;ans = Integer.MAX_VALUE;arr = new int[]{1, 5, 25, 125, 625, 3125, 15625, 78125};set = new HashSet<>();for(int a : arr) {set.add(a);}dfs(s, "0", 0, s.length());return ans == Integer.MAX_VALUE ? -1 : ans;}
}