题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法
典型的搜索解法,时间复杂度为O(N!),空间复杂度为O(N)。
class Solution {
private List<List<Integer>> list = new ArrayList();
public List<List<Integer>> permute(int[] nums) {
int[] book = new int[nums.length];
List<Integer> once = new ArrayList();
dp(0, book, once, nums);
return list;
}
public void dp(int step, int[] book, List<Integer> once, int[] nums){
if(step == book.length){
list.add(new ArrayList(once));
return;
}
for(int i= 0; i < nums.length; i++){
if(book[i] == 0){
book[i] = 1;
once.add(nums[i]);
dp(step + 1, book, once, nums);
once.remove(once.size() - 1);
book[i] = 0;
}
}
}
}