您的位置:首页 > 其它

leetcode解题方案--046--Permutations

2017-11-25 15:57 411 查看

题目

Given a collection of distinct 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],

[3,2,1]

]

分析

这道题我AC最快,时间复杂度最高,超越了0.44的人

我用了之前一个求下一个全排列的方法,对于每一个数组求下一个全排,转成list,扔进return里

下面是代码。代码也是又臭又长

public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> re = new LinkedList<List<Integer>>();
int length = nums.length;
int totalNum = 1;
while (length >= 1) {
totalNum = totalNum*length;
length--;
}
for (int i = 0; i<totalNum;i++) {
List<Integer> aa = Arrays.stream(nums)
.boxed()
.collect(Collectors.toList());
re.add(aa);
nextPermutation(nums);
}
return re;

}

public static void nextPermutation(int[] nums) {
int index = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i - 1] < nums[i]) {
index = i - 1;
break;
}
}
if (index == -1) {
Arrays.sort(nums);
return;

}

int flag = nums[index];
int minIndex = index + 1;
int min = nums[minIndex];
for (int i = index + 1; i < nums.length; i++) {
if (nums[i] > flag && nums[i] < min) {
min = nums[i];
minIndex = i;
}
}
int tmp = nums[index];
nums[index] = nums[minIndex];
nums[minIndex] = tmp;
int start = index + 1;

if (start < nums.length - 1) {
for (int i = start + 1; i < nums.length; i++) {
int tmp1 = nums[i];
int j = i;
while (j > start && tmp1 < nums[j - 1]) {
nums[j] = nums[j - 1];
j--;
}
nums[j] = tmp1;
}
}
}


AC之后我又想了想,正常应该怎么做,想到了下面这种方法:

list<list<Integer>>func(int[] nums){
//如果数组只有一个元素
if(。。)
return new list<Integer>(只包含这一个元素)
for(int i = 0; i<nums.length; i++) {
int[]newnums = 原数组除掉nums[i];
list<list<Integer>> list = func();
//遍历list,在每个子list中加入nums[i]
}
return list;

}


看到有人说可以用dfs的,觉得应该是种更好的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: