AcWing 93. 递归实现组合型枚举 (组合递归)

相比较上面的排列枚举,这个题把重复的去掉了,可在排列时增加序列性,实施起来就是枚举后位>前位

Problem

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, m;
    static int a[] = new int[50];

    public static void dfs(int u, int start) {
        if (u + n - start < m) return;  //剪枝

        if (u > m) {
            for (int i = 1; i <= m; i++)
                pw.print(a[i] + " ");
            pw.println();
            return;
        }

        for (int i = start; i <= n; i++) {
            a[u] = i;
            dfs(u + 1, i + 1);
        }
    }

    public static void main(String[] args) throws IOException {

        String[] s = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        dfs(1, 1);

        pw.flush();
        pw.close();
        br.close();
    }

}

你可能感兴趣的:(基础算法)