求1-n的第m个最小序列。
参考C++的next_permutation方法
博客链接 http://www.cnblogs.com/eudiwffe/p/6260699.html
寻找seq下一序列:
从后向前找到第一个a[i-1]<a[i];
从[i,end]找到第一个满足a[k]>a[i-1]的k值。由于[j,end]是降序的,所以是大于a[i-1]的最小值。
交换a[i-1],a[k]
将[i,end]倒序,因为[i,end]是降序的,所以倒置,从而得到当前序列的下一序列。
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main_1027 { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); int[] seq = new int[n + 1]; for (int i = 1; i <= n; i++) { seq[i] = i; } for(int p = 2; p <= m;p++) { getSequence(seq, n); } print(seq); } } public static void getSequence(int[] seq, int n) { for (int i = n; i > 1 ; i--) { while (seq[i] < seq[i - 1]){ i--; } int k = n; // while (seq[k--] < seq[i]) ; for (k = n; k >= i; k--) { if (seq[k] >= seq[i - 1]) { break; } } swap(seq, i - 1, k); reverse(seq, i, n); return; } } public static void swap(int[] seq, int i, int j) { int temp = seq[i]; seq[i] = seq[j]; seq[j] = temp; } public static void reverse(int[] seq, int j, int end) { while (j < end) { swap(seq, j++, end--); } } public static void print(int[] seq){ for(int i = 1; i < seq.length-1;i++){ System.out.print(seq[i]+" "); } System.out.println(seq[seq.length-1]); } }