Saturday, October 6, 2012

Generate all the permutations of 1.. N integer numbers

2 comments:

  1. public static void printPerm(List list, int k, String str) {

    if (k == 0) {
    System.out.println(str);
    }
    else {
    for(int i = 0; i < list.size(); i++) {
    Integer next = list.remove(i);
    printPerm(list, k-1, str + next);
    list.add(i, next);
    }
    }
    }


    With a simple variation you can generate all the combination of size k:

    public static void comb(List list, int k, String str) {

    if (k == 0) {
    System.out.println(str);
    }
    else {
    for(int i = 0; i < list.size(); i++) {
    ArrayList tmp = new ArrayList(list);
    String next = tmp.remove(i);
    comb(list, k-1, str + next);
    }
    }
    }

    ReplyDelete