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]
]
给出数列列出全部的排列组合,首先想到递归,然后是回溯的思路
比如对于1 , 如果在 2 3的排列组合都求出的情况下
只需将1 与 每一个组合中的每一个数交换一次就是最后的结果了
因此递归函数需要三个参数:条件数组num[],结果lists,当前index
函数功能:在当前index之后的排列完成的情况下加入当前index形成新的组合,删除原先组合
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if (nums.length !=0) {
rPermute(nums,lists,0);
}
return lists;
}
public void rPermute(int[]nums,List<List<Integer>> lists, int index) {
if (index != nums.length - 1) {
rPermute(nums, lists, index + 1);
} else {
List<Integer> firstList = new ArrayList<Integer>();
firstList.add(nums[index]);
lists.add(firstList);
return;
}
//保存原先的组合数量
int listSize = lists.size();
for (int i = 0 ; i < listSize; i++) {
List<Integer> list = lists.get(i);
int size = list.size();
//在每一个组合中加入新的元素
for (int j = 0; j <= size; j++) {
List<Integer> tmpList = new ArrayList<Integer>(list);
tmpList.add(j, nums[index]);
lists.add(tmpList);
}
}
//删除原先的组合
for (int i = 0; i < listSize; i++) {
lists.remove(0);
}
}