蛮力法——找出自然数1-n中任取r个数的所有组合

题目描述

找出从自然数1~n中任取r个数的所有组合。
例子:截至数3,2个数组合
自然数1~3中2个数的组合有:
1 2
1 3
2 3
注意:1 3,3 1被认为是同一种组合方案

输入格式:

输入给出截止数字和组合中数字数量(类型为整形),中间以逗号(,)隔开

输入样例:

3,2

输出样例:

自然数1~3中2个数的任意组合有:
1 2
1 3
2 3

代码:

#include<stdio.h>

#define MAX 100

int a[MAX];

void comb(int n, int r){

        int i, j;

        i = 0;

        a[i] = 1;

        do{

                if(a[i] - i <= n - r + 1){

                        if(i == r - 1){

                           for(j=0;j<r;j++){

                                printf("%4d",a[j]);

                                printf("\n");

                                a[i]++;

                                continue;                                

                        }

                        i++;

                        a[i]=a[i-1]+1;

                }

                else{

                        if(i==0)

                                return;

                                a[--i]++;

                }

        }while(1)

int main(){

        int x, y;

        printf("请规定截止数和几个数组合(用,分隔的整数):");

        scanf("%d,%d",&x,&y);

        printf("自然数1~%d中%d个数的任意组合有:\n",x,y);

        comb(x,y);

        return 0;

}        

好的,以下是回溯输出自然数1~n中任取r个数的所有组合的Java代码: ```java import java.util.ArrayList; import java.util.List; public class CombinationGenerator { public static void main(String[] args) { int n = 5; // 自然数1~n int r = 3; // 任取r个数 List<List<Integer>> combinations = generateCombinations(n, r); System.out.println("自然数1~" + n + "中任取" + r + "个数的所有组合:"); for (List<Integer> combination : combinations) { System.out.println(combination); } } private static List<List<Integer>> generateCombinations(int n, int r) { List<List<Integer>> combinations = new ArrayList<>(); List<Integer> currentCombination = new ArrayList<>(); backtrack(combinations, currentCombination, 1, n, r); return combinations; } private static void backtrack(List<List<Integer>> combinations, List<Integer> currentCombination, int start, int n, int r) { if (currentCombination.size() == r) { combinations.add(new ArrayList<>(currentCombination)); return; } for (int i = start; i <= n; i++) { currentCombination.add(i); backtrack(combinations, currentCombination, i + 1, n, r); currentCombination.remove(currentCombination.size() - 1); } } } ``` 代码中的 `generateCombinations` 方接受两个参数:`n` 表示自然数1~n,`r` 表示任取r个数。它返回一个 `List<List<Integer>>` 对象,其中每个 `List<Integer>` 对象表示一种组合。代码中使用了回溯来生成所有组合。具体来说,我们从1开始遍历到n,将每个数都加入当前组合中,然后递归地向后遍历,直到组合的长度达到r。如果当前组合的长度等于r,则将它加入结果集中,然后回溯到上一个状态,继续遍历下一个数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值