题目
- 给定一个不含重复数字的数组
nums
,返回其所有可能的全排列 。
代码
1. 非递归实现,借助栈
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Permutations {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3, 4};
List<List<Integer>> permutations = solution.permute(nums);
for (List<Integer> permutation : permutations) {
System.out.println(permutation);
}
}
}
class Solution {
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
List<List<Integer>> ans = new ArrayList<>();
Stack<List<Integer>> stack = new Stack<>();
stack.push(new ArrayList<>());
while (!stack.isEmpty()) {
List<Integer> currentPath = stack.pop();
if (currentPath.size() == n) {
ans.add(currentPath);
} else {
for (int element : nums) {
if (!currentPath.contains(element)) {
List<Integer> newPath = new ArrayList<>(currentPath);
newPath.add(element);
stack.push(newPath);
}
}
}
}
return ans;
}
}
2. 递归实现
import java.util.ArrayList;
import java.util.List;
class Solution {
List<List<Integer>> ans;
boolean[] visited;
List<Integer> path;
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
ans = new ArrayList<>();
visited = new boolean[n];
path = new ArrayList<>();
loop(nums, 0, n);
return ans;
}
public void loop(int[] nums, int len, int n) {
if (len == n) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < n; i ++) {
if (visited[i] == true) {
continue;
} else {
visited[i] = true;
path.add(nums[i]);
loop(nums, len + 1, n);
path.remove(path.size() - 1);
visited[i] = false;
}
}
}
}