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]
.
这道题很不幸我没有AC,我的解题思路就是在不同位置间次插入数字,时间复杂度O(N^3)。但是,由于自己设计算法本身的问题,总是出现重复的结果。
import java.util.ArrayList;
public class Permutations {
public static void main(String args[]){
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int[] n = {5,4,6,2};
int size = n.length;
int time = 0;
int total = 1;
int i = 0;
for(i =0; i < size; i++){
total = total * (i+1);
}
for(i = 0 ;i < total;i++)
{
ArrayList<Integer> r = new ArrayList<Integer>();
result.add(r);
}
for(i =0; i < size; i++){
time = total/(i + 1);
for(int q = 0;q < i+1; q++){
for(int j = 0; j<time; j++){
ArrayList<Integer> rr = result.get(q+(i+1)*j);
rr.add(q,n[i]);
}
}
}
System.out.println(result);
}
}
进而,我查阅了他人 的AC思路,经测试AC。
这类题目面试很常见,应当注意。
Analysis:
We want to get permutations, which is mainly about swap values in the list.
Consider:
a --> a
ab --> ab, ba
abc --> abc, acb, bac, bca, cab, cba.
...
where for the length of n, the permutations can be generated by
(1) Swap the 1st element with all the elements, including itself.
(2) Then the 1st element is fixed, go to the next element.
(3) Until the last element is fixed. Output.
It's more clear in the figure above. The key point is to make the big problem into smaller problem, here is how to convert the length n permutation into length n-1 permutation problem.
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> cal = new ArrayList<Integer>();//代表一种排列
ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();//总结果
int len = num.length;
int[] used = new int[len];//记录每一个位置的元素是否被使用过
getpermute(num, used, len, cal, re);
return re;
}
public void getpermute(int[] num, int[] used, int len, ArrayList<Integer> cal, ArrayList<ArrayList<Integer>> re){
if(cal.size() == len){
ArrayList<Integer> temp = new ArrayList<Integer>(cal);
re.add(temp);
return;
}
for(int i=0; i<len; i++){
if(used[i] == 0){
cal.add(num[i]);
used[i]=1;
getpermute(num,used,len,cal,re);//思路和我最初设计的一样,使用递归,不知道有没有比递归更简易的方法
used[i]=0;
cal.remove(cal.size()-1);//去掉用过的最后的元素,重新从末尾开始permutation
}
}
}
}