全排列问题,今天看到微博上有人说清华的研究生复试上机试题有一道全排列问题,貌似学生们回答的不好。
想起以前在leetCode上面也刷过全排列问题,就又重新AC了一次。
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]
http://oj.leetcode.com/problems/permutations/
解题思路:字符交换加dfs。
将第0个字符和从第0开始的每个字符进行交换,对于交换后的结果,再从第1个字符开始交换。一直到最后一个字符。
AC代码:
public class Solution {
void dfs(int i, int[] num,ArrayList<ArrayList<Integer>> result) {
if(i==num.length) {
for(int j=0;j<num.length;j++) {
tmp.add(num[j]);
}
result.add(tmp);
return;
}
for(int j=i;j<num.length;j++) {
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
dfs(i+1,num,result);
tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
}
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num==null||num.length==0) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
result.add(tmp);
return result;
}
dfs(0,num,result);
return result;
}
}