基本思路:
基本思路就是回溯,先设想其第一步的一种情况,然后再撤销这个设想,回溯到上一步看看还能不能有别的情况,通过深度遍历递归将所有可能性都列举出来,这就是回溯。
通过构建一个树我们可以更清楚的观察到回溯的整个过程
代码实现:
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> aa = new ArrayList<List<Integer>>();
List<Integer> bb = new ArrayList<Integer>();
//先将所有数字填充进小链表bb里
for (int num : nums) {
bb.add(num);
}
//数组有几个数字
int n = nums.length;
back(n, bb,aa, 0);
return aa;
}
public void back(int n, List<Integer> bb, List<List<Integer>>aa, int first) {
//当first==n时说明这条数组遍历变了一次得到了一个叶节点,将其添加进大链表aa中
if (first == n) {
aa.add(new ArrayList<Integer>(bb));
}
for (int i = first; i < n; i++) {
Collections.swap(bb, first, i);
//继续递归填下一个数
back(n, bb, aa, first + 1);
//撤销操作
Collections.swap(bb, first, i);
}
}
}