|
| 1 | +package com.fishercoder.solutions.fourththousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +public class _3211 { |
| 9 | + public static class Solution1 { |
| 10 | + public List<String> validStrings(int n) { |
| 11 | + List<String> result = new ArrayList<>(); |
| 12 | + for (int i = n / 2; i <= n; i++) { |
| 13 | + List<String> combinations = generateCombinations(i, n - i); |
| 14 | + for (String s : combinations) { |
| 15 | + if (noAdjacentZeroes(s)) { |
| 16 | + result.add(s); |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + return result; |
| 21 | + } |
| 22 | + |
| 23 | + private boolean noAdjacentZeroes(String s) { |
| 24 | + for (int i = 0; i < s.length() - 1; i++) { |
| 25 | + if (s.charAt(i) == '0' && s.charAt(i + 1) == '0') { |
| 26 | + return false; |
| 27 | + } |
| 28 | + } |
| 29 | + return true; |
| 30 | + } |
| 31 | + |
| 32 | + private List<String> generateCombinations(int ones, int zeroes) { |
| 33 | + int[] nums = new int[ones + zeroes]; |
| 34 | + int i = 0; |
| 35 | + while (ones-- > 0) { |
| 36 | + nums[i++] = 1; |
| 37 | + } |
| 38 | + return permuteUnique(nums); |
| 39 | + } |
| 40 | + |
| 41 | + private List<String> permuteUnique(int[] nums) { |
| 42 | + Set<String> set = new HashSet<>(); |
| 43 | + set.add(""); |
| 44 | + set = recurse(nums, set, 0); |
| 45 | + List<String> list = new ArrayList<>(); |
| 46 | + for (String s : set) { |
| 47 | + list.add(s); |
| 48 | + } |
| 49 | + return list; |
| 50 | + } |
| 51 | + |
| 52 | + private Set<String> recurse(int[] nums, Set<String> set, int pos) { |
| 53 | + if (pos == nums.length) { |
| 54 | + return set; |
| 55 | + } |
| 56 | + Set<String> newSet = new HashSet<>(); |
| 57 | + for (String s : set) { |
| 58 | + for (int i = 0; i <= s.length(); i++) { |
| 59 | + StringBuilder sb = new StringBuilder(s); |
| 60 | + sb.insert(i, nums[pos]); |
| 61 | + newSet.add(sb.toString()); |
| 62 | + } |
| 63 | + } |
| 64 | + return recurse(nums, newSet, pos + 1); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments