LeetCode——全排列

给定一个没有重复数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
 
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class FullSort {

private List<List<Integer>> lists = new ArrayList<List<Integer>>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0) {
return lists;
}
else{
allSort(nums,new Stack<Integer>());
return lists;
}
}
//递归函数
public void allSort(int[]nums,Stack<Integer> stack)
{
//终止条件
if(stack.size() == nums.length )
{
lists.add(new ArrayList<Integer>(stack));
return;
}
for (int num : nums) {
if( stack.contains(num) ) {
continue;
}
stack.push(num);
allSort(nums,stack);
    //出栈
stack.pop();
}
}
}
 
 

猜你喜欢

转载自www.cnblogs.com/cdlyy/p/12081146.html