首页 > 试题广场 >

选择物品

[编程题]选择物品
  • 热度指数:4174 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

个物品可供选择,必须选择其中个物品,请按字典序顺序输出所有选取方案的物品编号

等被认为是同一种方案,输出字典序最小的即可

数据范围:
进阶:时间复杂度,空见复杂度

输入描述:
对于每一组测试数据, 每行输入个数




输出描述:
对于每组输入样例,按字典序输出所有方案选择物品的编号,每种方案占一行
示例1

输入

4 1

输出

1
2
3
4
示例2

输入

5 2

输出

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

终于有一道我能做的题了,,,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
    public static ArrayList> res = new ArrayList();
    public static ArrayList path = new ArrayList();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] params = br.readLine().trim().split(" ");
        int n = Integer.parseInt(params[0]), m = Integer.parseInt(params[1]);
        dfs(n, m, 1);
        for(ArrayList items: res){
            for(Integer elem : items){
                System.out.print(elem + " ");
            }
            System.out.println();
        }
    }
    private static void dfs(int n, int m, int index) {
        if(path.size() == m){
            res.add(new ArrayList(path));
            return;
        }
        for(int i = index; i <= n; i++){
            path.add(i);
            dfs(n, m, i + 1);
            path.remove(path.size() - 1);
        }
    }
}
发表于 2022-03-02 10:32:31 回复(0)