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] ]
给定一个不同数字的集合,返回所有可能的排列.
用递归写的全排列.
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// java 8的stream类
// 把int[]变为Integer[],再变为List<Integer> 看来java8的特性要了解啊
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
permute(ans,list,0);
return ans;
}
public void permute(List<List<Integer>> ans, List<Integer> list, int begin) {
if (begin == list.size() - 1) {
// 注意List.add直接加的是list引用,需要new一个新的list对象
List<Integer> newlist = new ArrayList<>(list);
ans.add(newlist);
}
for (int i = begin; i < list.size(); i++) {
swap(list, i, begin);
permute(ans, list, begin + 1);
swap(list, i, begin);
}
}
public void swap(List<Integer> list, int a, int b) {
Integer temp = list.get(a);
list.set(a, list.get(b));
list.set(b, temp);
}
运行时间比较长,找到一个运行时间4ms的大神代码.
http://blog.csdn.net/xiayu98020214/article/details/45583573
public List<List<Integer>> permute1(int[] num) {
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
res.add(new ArrayList<Integer>());
for (int n : num) {
int size = res.size();
for (; size > 0; size--) {
List<Integer> r = res.pollFirst();
for (int i = 0; i <= r.size(); i++) {
List<Integer> t = new ArrayList<Integer>(r);
t.add(i, n);
res.add(t);
}
}
}
return res;
}