【Leetcode】Permutations

本文深入探讨了LeetCode上关于全排列问题的解决方法,包括核心算法和具体实例解析。

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

题目链接:https://leetcode.com/problems/permutations/

题目:

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].

o see which companies asked this question

思路:

数组下标的三皇后问题,实质是全排列问题。唯一不同 都是,本题全排列的是数组的下标。只要做个对应转化就好了。

算法:

	List<List<Integer>> iLists = new ArrayList<List<Integer>>();

	public List<List<Integer>> permute(int[] nums) {
		this.n = nums.length;
		this.cl = new int[n];
		this.n2 = nums;
		dspPermute(0);
		return iLists;
	}

	int[] n2;
	int cl[] = null;
	int n = 0;

	void dspPermute(int cur) {
		if (cur == n) {
			List<Integer> list = new ArrayList<Integer>();
			for (int i = 0; i < cl.length; i++) {
				list.add(cl[i]);
			}
			iLists.add(list);
		} else {
			for (int i = 0; i < n; i++) { // 探索每一列
				cl[cur] = n2[i];// 选择n[i]为第cur个数
				boolean flag = true;
				for (int j = 0; j < cur; j++) {// cur前所有行 若无冲突
					if (cl[cur] == cl[j])
						flag = false;
				}
				if (flag == true) {
					dspPermute(cur + 1);
				}
			}
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值