public static List<Integer> next_permutation(List<Integer> p) {
	  int k = p.size() - 2;
	  while (k >= 0 && p.get(k) >= p.get(k + 1)) {
	    --k;
	  }
	  if (k == -1) {
	    return Collections.emptyList();  // p is the last permutation.
	  }

	  int l = 0;
	  for (int i = k + 1; i < p.size(); ++i) {
	    if (p.get(i) > p.get(k)) {
	      l = i;
	    } else {
	      break;
	    }
	  }
	  swap(p, k, l);

	  // Produce the lexicographically minimal permutation.
	  Collections.reverse(p.subList(k + 1, p.size()));
	  return p;
	}