acm每日一练之擅长排列的小明

描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入
第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出
在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
2
3 1
4 2
样例输出
1
2
3
12
13
14
21
23
24
31
32
34
41
42
43

code;

import java.io.PrintWriter;
import java.util.Scanner;

public class Test {

    static Scanner scin = new Scanner(System.in);

    static PrintWriter scout = new PrintWriter(System.out);

    static int n, m;

    static int rcd[] = new int[10];// 用于输出

    static int num[] = new int[10]; // 存放输入数

    static int used[] = new int[10];// 判断是否已经使用

    public static void main(String[] args) {
        int t, i;
        for (i = 0; i < 10; i++)
            num[i] = i + 1;
        t = scin.nextInt();
        while (t-- > 0) {
            n = scin.nextInt();
            m = scin.nextInt();

            for (i = 0; i < 10; i++)
                used[i] = 1;
            unrepeat_permutation(0);
        }
        scout.close();
    }

    static void unrepeat_permutation(int l) {
        int i;
        if (l == m) {
            for (i = 0; i < m; i++)
                scout.print(rcd[i]);
            scout.println();
            scout.flush();
            return;
        }
        for (i = 0; i < n; i++) // 从1开始枚举n个数
        {
            if (used[i] > 0) {
                used[i]--; // 使用次数减1
                rcd[l] = num[i]; // 把num[i]的值放在l的位置
                unrepeat_permutation(l + 1); // 填下一个数
                used[i]++; // 恢复使用--以某一前缀开头的递归运行完后要做到不影响其它前缀的递归,所以要恢复;
            }
        }
    }
}

code2:

import java.util.Scanner;

public class Main{
    public static int n, r;

    public static StringBuffer string;

    public static boolean mark[];

    public static void dfs(int k) {
        if (k < r) {
            for (int i = 1; i <= n; i++) {
                if (!mark[i]) {
                    string.append(i);
                    mark[i] = true;
                    dfs(k + 1);
                    mark[i] = false;
                    string.deleteCharAt(k);
                }
            }
        }
        else {
            System.out.println(string);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int cases = scanner.nextInt();
        while (cases-- != 0) {
            n = scanner.nextInt();
            r = scanner.nextInt();
            mark = new boolean[n + 1];
            string = new StringBuffer();
            dfs(0);
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值