【重点】【回溯】46.全排列

文章介绍了一种使用深度优先搜索(DFS)算法解决字符串排列问题的Java代码实现,Solution类中定义了permute方法进行全排列计算,涉及递归、数组交换等技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
跟另外一个题目很像:字符串的排列

Python

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = list()
        self.dfs(nums, 0, res)
        return res
    
    def dfs(self, nums, start, res):
        if start == len(nums) - 1:
            res.append(nums.copy()) # list自带copy方法
            return 
        
        for i in range(start, len(nums), 1):
            nums[start], nums[i] = nums[i], nums[start]
            self.dfs(nums, start + 1, res)
            nums[start], nums[i] = nums[i], nums[start]

Java

法1:DFS,最佳解法

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length == 0) {
            return res;
        }
        dfs(nums, 0, res);

        return res;
    }

    public void dfs(int[] nums, int curInx, List<List<Integer>> res) {
        if (curInx == nums.length - 1) {
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < nums.length; ++i) {
                tmp.add(nums[i]);
            }
            res.add(tmp);
            return;
        }
        
        for (int i = curInx; i < nums.length; ++i) {
            swap(nums, curInx, i);
            dfs(nums, curInx + 1, res);
            swap(nums, curInx, i);
        }
    }

    public void swap(int[] array, int i, int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值