Skip to content

Instantly share code, notes, and snippets.

@gabhi
Created June 21, 2014 17:45
Show Gist options
  • Save gabhi/b2f519042a7657647b44 to your computer and use it in GitHub Desktop.
Save gabhi/b2f519042a7657647b44 to your computer and use it in GitHub Desktop.
http://exceptional-code.blogspot.com/2012/09/generating-all-permutations.html
@gabhi
Copy link
Author

gabhi commented Jun 21, 2014

void generatePermutations(char[] arr, int size, char[] branch, int level, boolean[] visited)
{
if (level >= size-1)
{
System.out.println(branch);
return;
}

for (int i = 0; i < size; i++)
{
    if (!visited[i])
    {
        branch[++level] = arr[i];
        visited[i] = true;
        generatePermutations(arr, size, branch, level, visited);
        visited[i] = false;
        level--;
    }
}

}

@gabhi
Copy link
Author

gabhi commented Jun 21, 2014

void combine(char[] arr, int k, int startId, char[] branch, int numElem)
{
if (numElem == k)
{
System.out.println(Arrays.toString(branch));
return;
}

for (int i = startId; i < arr.length; ++i)
{
    branch[numElem++] = arr[i];
    combine(arr, k, ++startId, branch, numElem);
    --numElem;
}

}

@gabhi
Copy link
Author

gabhi commented Jun 21, 2014

void powerSet(char[] arr)
{
for (int i = 0; i < arr.length; ++i)
{
char[] branch = new char[i];
combine(arr, i, 0, branch, 0);
}
}

@gabhi
Copy link
Author

gabhi commented Jun 21, 2014

public static Set<Set> powerSet(Set originalSet) {
Set<Set> sets = new HashSet<Set>();
if (originalSet.isEmpty()) {
sets.add(new HashSet());
return sets;
}
List list = new ArrayList(originalSet);
T head = list.get(0);
Set rest = new HashSet(list.subList(1, list.size()));
for (Set set : powerSet(rest)) {
Set newSet = new HashSet();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
return sets;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment