四个数的排列组合问题

主要是学习其中的递归思想

下面是JAVA代码实现:

public class ArrayCombination {
 
    static int[] a = {1, 2, 3};
    static int count = 0;
 
    public static void main(String[] args) {
        permutation(0, a.length-1);
        System.out.println("一共有" + count + "种组合");
    }
     
    public static void permutation(int m, int n) {
        int i;
        if (m == n) {
            display(a);
            count++;
        }
        for (i = m; i <= n; i++) {
            swap(i,m);
            permutation(m + 1, n);
            swap(i,m);
        }
    }
 
    public static void display(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
        System.out.println();
    }
 
    public static void swap(int x,int y){
        int temp = a[x];
        a[x] = a[y];
        a[y] = temp;       
    }
}


### Scala 实现四个数字的排列组合 在 Scala 中实现四个数字的排列组合,可以通过递归或迭代的方式生成所有可能的排列。以下是基于引用内容和专业方法的实现方案。 #### 方法一:递归实现 递归是一种常见的生成排列的方法。通过每次固定一个数字,并对剩余的数字进行递归调用,最终可以得到所有的排列组合。 ```scala object Permutation { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4) // 定义四个数字 val result = permute(numbers) println(s"共有 ${result.size} 种排列") result.foreach(println) } def permute(nums: List[Int]): List[List[Int]] = nums match { case Nil => List(Nil) case _ => for { (x, i) <- nums.zipWithIndex xs = nums.take(i) ::: nums.drop(i + 1) ys <- permute(xs) } yield x :: ys } } ``` 上述代码中,`permute` 函数通过模式匹配和列表操作实现了递归排列生成[^1]。对于每个数字 `x`,将其从原列表中移除后递归生成剩余数字的排列,并将 `x` 添加到每种排列的前面。 #### 方法二:使用集合操作 Scala 的集合库提供了丰富的功能,可以利用这些功能简化排列组合的实现。以下代码展示了如何使用集合操作生成排列。 ```scala object Permutation { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4) // 定义四个数字 val result = numbers.permutations.toList println(s"共有 ${result.size} 种排列") result.foreach(println) } } ``` 在 Scala 中,`permutations` 是集合的一个内置方法,可以直接生成所有可能的排列[^2]。此方法简单高效,适合快速实现排列组合问题。 #### 方法三:手动迭代实现 如果需要更灵活的控制,可以通过嵌套循环手动实现排列组合。以下是一个示例: ```scala object Permutation { def main(args: Array[String]): Unit = { val numbers = List(1, 2, 3, 4) // 定义四个数字 val result = for { i <- numbers.indices j <- numbers.indices if j != i k <- numbers.indices if k != i && k != j l <- numbers.indices if l != i && l != j && l != k } yield List(numbers(i), numbers(j), numbers(k), numbers(l)) println(s"共有 ${result.size} 种排列") result.foreach(println) } } ``` 此代码通过嵌套循环逐一选择每个位置上的数字,确保没有重复选择,从而生成所有排列[^3]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值