LeetCode Permutations

本文详细介绍了全排列问题的解题思路和代码实现,包括使用字符交换加深度优先搜索(DFS)的方法来解决。并通过LeetCode上的题目实例进行演示。

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

全排列问题,今天看到微博上有人说清华的研究生复试上机试题有一道全排列问题,貌似学生们回答的不好。
想起以前在leetCode上面也刷过全排列问题,就又重新AC了一次。
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]
http://oj.leetcode.com/problems/permutations/
解题思路:字符交换加dfs。
将第0个字符和从第0开始的每个字符进行交换,对于交换后的结果,再从第1个字符开始交换。一直到最后一个字符。
AC代码:

public class Solution {
    void dfs(int i, int[] num,ArrayList<ArrayList<Integer>> result) {
        if(i==num.length) {
            for(int j=0;j<num.length;j++) {
                tmp.add(num[j]);
            }
            result.add(tmp);
            return;
        }
        for(int j=i;j<num.length;j++) {
            int tmp = num[i];
            num[i]  = num[j];
            num[j]  = tmp;
            dfs(i+1,num,result);
            tmp = num[i];
            num[i]  = num[j];
            num[j]  = tmp;
        }
    }
    
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        if(num==null||num.length==0) {
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            result.add(tmp);
            return result;
        }
        dfs(0,num,result);
        return result;
    }
}




评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值