java-生成1~n的序列
阿新 • • 發佈:2017-10-03
mut nbsp java dem str scanner [0 length close
import java.util.Scanner; /** * 生成1~n的排列 * @author NEU-2015 * */ public class Demo { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n; int[] array; while (input.hasNext()) { n = input.nextInt(); array= new int[n]; print_permutation(n, array, 0); } input.close(); } private static void print_permutation(int n, int[] array, int i) { if (i == n) { //遞歸邊界 for (int j = 0; j < array.length; j++) { System.out.print(array[j] + " "); } System.out.println(); }else { for (int k = 1; k <= n; k++) { //嘗試在array[i]中填入各種整數i boolean flag = true; for (int m = 0; m < i; m++) { if (array[m] == k) { //如果i已經在array[0]~array[i-1]出現過 則不能再選 flag = false; } }if (flag) { array[i] = k; print_permutation(n, array, i + 1); } } } } }
java-生成1~n的序列