题目:https://oj.leetcode.com/problems/permutations/
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].
算法分析:时间复杂度O(n!),空间复杂度O(n)
public class Solution {
public List<List<Integer>> permute(int[] num) {
if(num==null || num.length==0) {
return null;
}
List<List<Integer>> results=new ArrayList<List<Integer>>();
permute(num,0,results);
return results;
}
private void permute(int[] num,int index,List<List<Integer>> results) {
if(index==num.length) {
List<Integer> list=new ArrayList<Integer>();
for(int data : num) {
list.add(data);
}
results.add(list);
}else {
for(int i=index;i<num.length;i++) {
swap(num,index,i);
permute(num,index+1,results);
swap(num,index,i);
}
}
}
private void swap(int[] num,int x,int y) {
int temp=num[x];
num[x]=num[y];
num[y]=temp;
}
}
本文详细介绍了使用Java语言实现全排列算法的过程,包括核心代码分析、时间与空间复杂度的评估,以及具体实例演示。
311

被折叠的 条评论
为什么被折叠?



