题目链接: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);
}
}
}
}