码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——全排列

时间:2019-12-22 21:45:41      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:ret   perm   stack   返回   输入   turn   lis   private   函数   

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

示例:

输入: [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();
}
}
}
 
 

LeetCode——全排列

标签:ret   perm   stack   返回   输入   turn   lis   private   函数   

原文地址:https://www.cnblogs.com/cdlyy/p/12081146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!