The arrangements may be output in any order example

This preview shows 11 out of 13 pages.

words that can be formed from unique letters in that string. The arrangements may be output in any order. – Example: combinations("GOOGLE", 3) outputs the sequence of lines at right. To simplify the problem, you may assume that the string s contains at least k unique characters. LEG LEO LGE LGO LOE LOG OEG OEL OGE OGL OLE OLG EGL EGO ELG ELO EOG EOL GEL GEO GLE GLO GOE GOL
Image of page 11

Subscribe to view the full document.

12 Initial attempt public static void combinations(String s, int length) { combinations(s, "", length); } private static void combinations(String s, String chosen, int length) { if (length == 0) { System.out.println(chosen) ; // base case: no choices left } else { for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); if (!chosen.contains(ch)) { String rest = s.substring(0, i) + s.substring(i + 1); combinations(rest, chosen + ch, length - 1); } } } } Problem: Prints same string multiple times.
Image of page 12
13 Exercise solution public static void combinations(String s, int length) { Set<String> all = new TreeSet<String>(); combinations(s, "", all , length); for (String comb : all) { System.out.println(comb); } } private static void combinations(String s, String chosen, Set<String> all , int length) { if (length == 0) { all.add(chosen) ; // base case: no choices left } else { for (int i = 0; i < s.length(); i++) { String ch = s.substring(i, i + 1); if (!chosen.contains(ch)) { String rest = s.substring(0, i) + s.substring(i + 1); combinations(rest, chosen + ch, all, length - 1); } } } }
Image of page 13
You've reached the end of this preview.
  • Spring '08
  • SR
  • Computer Science, Backtracking, private static void, MARTY MARYT, String ch, static void combinations

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern