做法有很多,我采取的思路也很简单,就是简单的递归....先将数组排序,按照顺序每次插入一个数字并将当前的排列插入结果集合.....最后返回的即是全排列。
但是!!! 一直都是TLE,而且出错的数据也不大......找了半天原因后来发现自己经常忽略的一点!!!! JAva传递的都是对象,所以在递归和插入结果集合的时候我们不能直接将
当前List插入(因为其可能在之后的递归中被修改),应该新建一个或clone来插入或递归.......
public class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] S) {
Arrays.sort(S);
List<Integer> tmp = new ArrayList<Integer>();
fun(tmp,S,0,0);
return res;
}
void fun(List<Integer> tmp,int[] S,int count,int dep)
{
res.add(tmp);
int num = S.length;
if(dep==num)
{
return ;
}
for(int i=count;i<num;i++)
{
List<Integer> ttt = new ArrayList(tmp);
ttt.add(S[i]);
fun(ttt,S,i+1,dep+1);
}
}
}