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].
给定一组数字,返回所有的可能的组合。
比如:
[1,2,3] 有下面的组合:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2],
and [3,2,1].
建立树,并进行递归 参考博客:http://blog.csdn.net/tuantuanls/article/details/8717262 思路二
建立一棵树,比如说:
public class Solution
{
public ArrayList<ArrayList<Integer>> permute(int[] num)
{
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
permute(num, 0, result);
return result;
}
void permute(int[] num, int start, ArrayList<ArrayList<Integer>> result)
{
if (start >= num.length) //终止条件,递归到末尾节点是,将数组转化为链表
{
ArrayList<Integer> item = convertArrayToList(num);
result.add(item);
}
for (int j = start; j <= num.length - 1; j++)
{
swap(num, start, j);//交换
permute(num, start + 1, result);//交换后子代递归
swap(num, start, j);//恢复到交换前的初始状态,以便于得出下一次的交换结果
}
}
private ArrayList<Integer> convertArrayToList(int[] num) //数组变链表
{
ArrayList<Integer> item = new ArrayList<Integer>();
for (int h = 0; h < num.length; h++)
item.add(num[h]);
return item;
}
private void swap(int[] a, int i, int j) //交换
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}版权声明:本文为博主原创文章,转载注明出处
原文:http://blog.csdn.net/evan123mg/article/details/46875467