力扣-11.9-46

在这里插入图片描述
回溯

class Solution {

    public static void dfs(int[] nums, int len, int depth, List<Integer> path, int[] used, List<List<Integer>> res) {
		if (depth == len) {
			res.add(new ArrayList<Integer>(path));
			return;
		}

		// 在非叶子结点处,产生不同的分支,这一操作的语义是:在还未选择的数中依次选择一个元素作为下一个位置的元素,这显然得通过一个循环实现。
		for (int i = 0; i < len; i++) {
			if (used[i] == 0) {
				path.add(nums[i]);
				used[i] = 1;

				dfs(nums, len, depth + 1, path, used, res);
				// 注意:下面这两行代码发生 「回溯」,回溯发生在从 深层结点 回到 浅层结点 的过程,代码在形式上和递归之前是对称的
				used[i] = 0;
				path.remove(path.size() - 1);
			}
		}
	}
    
    public List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        // 使用一个动态数组保存所有可能的全排列
        List<List<Integer>> res = new ArrayList<>();
        if (len == 0) {
            return res;
        }

        int[] used = new int[len];
        List<Integer> path = new ArrayList<>();

        dfs(nums, len, 0, path, used, res);
        return res;
    }
}

补充:(重要!!!
https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liweiw/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值