全排列算法(无重复元素时) --Java

public class Permutation {

    public static void permulation(int[] list, int start, int length) {
        int i;
        if (start == length) {//交换到最后一个数之后,start+1会等于length,这时输出list
            for (i = 0; i < length; i++)
                System.out.print(list[i] + " ");
            System.out.println();
        } else {
        	//!!递归
            for (i = start; i < length; i++) {
                swap(list, start, i);
                permulation(list, start + 1, length);
                swap(list, start, i);//每轮递归结束负责把list调成原来的样子再继续递归
            }
        }
    }
    //交换list中指定位置的元素
    public static void swap(int[] list, int start, int i) {
        int temp;
        temp = list[start];
        list[start] = list[i];
        list[i] = temp;
    }

    public static void main(String[] args) {
        int length = 3;
        int start =
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
全排列算法重复)是一种用于对一组元素进行全排列算法,即将给定的一组元素按照不同的顺序进行排列,且每个元素可以重复使用。 在Python中,我们可以使用递归和交换元素的方式来实现全排列算法重复)。具体步骤如下: 1. 定义一个递归函数permutations,该函数接受三个参数:nums(待排列的元素列表)、start(交换的起始位置)和result(存储排列结果的列表)。 2. 当start等于nums的长度,表示已经完成了一次排列,将当前的排列结果加入到result中。 3. 遍历从start到nums的长度的所有位置,依次将当前位置的元素与start位置的元素交换,并递归调用permutations函数。 4. 在递归调用结束后,将交换的元素再恢复为原来的顺序,以保证下一次交换的正确性。 下面是使用Python代码实现全排列算法重复)的例子: ```python def permutations(nums, start, result): if start == len(nums): result.append(nums[:]) for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums[start] permutations(nums, start + 1, result) nums[start], nums[i] = nums[i], nums[start] nums = [1, 2, 2] result = [] permutations(nums, 0, result) print(result) ``` 以上代码输出的结果是: ``` [[1, 2, 2], [1, 2, 2], [2, 1, 2], [2, 2, 1], [2, 2, 1], [2, 1, 2]] ``` 这就是全排列算法重复)的交换元素实现方式。通过递归和交换元素的方式,我们可以生成给定一组元素的所有排列结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值