力扣(LeetCode)46

栏目: 编程工具 · 发布时间: 6年前

内容简介:题目地址:题目描述:

题目地址:

https://leetcode-cn.com/probl...

题目描述:

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]

输出:

[

[1,2,3],

[1,3,2],

[2,1,3],

[2,3,1],

[3,1,2],

[3,2,1]

]

解答:

利用递归,我们可以认为,求一个数组的全排列,就是把这个数组中的每个位置的元素分别放在数组头部

然后求剩余元素的全排列,递归边界是剩余元素数量为1,也就是说当数组中只剩一个元素的时候,它的全

排列就是它本身。

java ac代码:

class Solution {
    List<List<Integer>>ans = new ArrayList(1000);
    public List<List<Integer>> permute(int[] nums) {
        perm(nums,0,nums.length-1);
        return ans;
    }
    
    void perm(int[] nums,int i,int j)
    {
        if(i == j)
        {
            List<Integer> temp = new ArrayList(nums.length);
            for(int k = 0;k < nums.length;k++)temp.add(nums[k]);
            ans.add(temp);
            return;
        }
        for(int k = i;k <= j;k++)
        {
            swap(nums,i,k);
            perm(nums,i+1,j);
            swap(nums,i,k);
        }
    }
    
    void swap(int[] nums,int i,int j)
    {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Numerical Methods and Methods of Approximation in Science and En

Numerical Methods and Methods of Approximation in Science and En

Karan Surana / CRC Press / 2018-10-31

ABOUT THIS BOOK Numerical Methods and Methods of Approximation in Science and Engineering prepares students and other readers for advanced studies involving applied numerical and computational anal......一起来看看 《Numerical Methods and Methods of Approximation in Science and En》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具