java:
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for(int num : nums) list.add(num);
int n = nums.length;
dfs(n, list, ans, 0);
return ans;
}
public void dfs(int n, List<Integer> list, List<List<Integer>> ans , int flag){
if(flag == n){
ans.add(new ArrayList<Integer>(list));
return;
}
for(int i = flag; i < n; i ++){
Collections.swap(list, flag, i);
dfs(n, list, ans, flag + 1);
Collections.swap(list, flag, i);
}
}
}
python3:
库函数虽迟但到🤪
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(itertools.permutations(nums))
回溯算法:
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def bt(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
bt(nums[:i]+nums[i+1:],tmp + [nums[i]])
bt(nums,[])
return res