LeetCode 46 Permutations

本文介绍了一种使用递归方法实现的不同数字集合的所有可能排列算法,并提供了一个Java程序实例。该算法通过元素间的交换来生成所有可能的排列组合。

一,问题描述
1,给定一个不同的数字的集合,返回所有可能的排列。
输入1 2 3
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

( 当如n个数, 那么一共有n!种不同的排序,例如n=4 ,那么total=24种不同排序)

2,采用递归的方法,对一个个元素交换着,进行判断,然后输出。

二,AC了的程序(采用Java来写的)

import java.awt.*;
import java.util.*;
import java.util.List;

public class Test2{
    List<List<Integer>> list=new ArrayList<List<Integer>>();
    public List<List<Integer>> permute(int []nums)
    {
        if(nums==null||nums.length==0)  //判断一下数组的长度是否为0以及数组元素是否为空,则返回空
        {
            return null;
        }
        int len=nums.length;
        int i=0;
        Sort(nums,i,len);


        return list;
    }
    public void Sort(int []nums,int begin, int end)
    {
        if(begin==end-1) //当判断到了最后一个元素时,则直接输出排序的结果
        {
            List<Integer> list1=new ArrayList<Integer>();
            for(int i=0;i<end;i++)
            {
                list1.add(nums[i]);
            }
            list.add(list1);
        }
        else
        {
            for(int i=begin;i<end;i++)
            {
                swap(nums,begin,i);   //首先对第一个数和第一个数交换,
                Sort(nums,begin+1,end);  //然后递归第二个数到末尾。
                swap(nums,begin,i);   //再把第一个数和第一个数交换回来。以便下一次循环使用。
            }
        }
    }

    public void swap(int []nums, int x,int y)  //交换数组的元素
    {
        int temp=nums[x];
        nums[x]=nums[y];
        nums[y]=temp;
    }


    public static void main(String []args)
    {
        Test2 test=new Test2();
        Scanner scan=new Scanner(System.in);
        int k=scan.nextInt();//输入数组的长度
        int []data;
        data=new int[k];

        for(int i=0;i<k;i++)
        {
            data[i]=scan.nextInt();
        }

        List<List<Integer>> list=test.permute(data);

        Iterator<List<Integer>> it1=list.iterator();
        while(it1.hasNext())//双层List的输出的格式。
        {
            List<Integer> list2=it1.next();
            Iterator<Integer>it2=list2.iterator();
            while(it2.hasNext())
            {
                int result=it2.next();
                System.out.print(result+" ");
            }
            System.out.println();
        }
    }
}

运行结果:
这里写图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值