CC150 8.5

8.5 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3 (e.g., 3 pairs of parentheses) output: ()()(), ()(()), (())(), ((()))

    private static Set<String> oneMorePar(String s)
    {
        Set<String> toReturn = new HashSet<>();
        for (int i = 0; i <= s.length(); i++)
        {
            // A little improvement
            if (i != 0 && s.charAt(i - 1) == '(')
            {
                continue;
            }

            String onlyLeft = s.substring(0, i) + "(" + s.substring(i, s.length());
            for (int j = i + 1; j <= onlyLeft.length(); j++)
            {
                String withRight = onlyLeft.substring(0, j) + ")" + onlyLeft.substring(j, onlyLeft.length());

                toReturn.add(withRight);
                System.out.println("Get:" + withRight);
            }
        }
        return toReturn;
    }

    private static Set<String> allP(int k)
    {
        if (k == 0)
        {
            return Collections.emptySet();
        }
        else if (k == 1)
        {
            return Collections.singleton("()");
        }

        Set<String> small = allP(k - 1);
        Set<String> toReturn = new HashSet<>();
        for (String r : small)
        {
            toReturn.addAll(oneMorePar(r));
        }
        return toReturn;
    }


你可能感兴趣的:(interview)