Permutations
2021/8/6 6:07:55
本文主要是介绍Permutations,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Constraint:
1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique.
Idea
Search:
if the size of permutation set is eaual to array size, add it to the final results list
For each number in the array in range [0, n):
if nums[i] is not visited, add it to the temp permuation set
repeat the search for other nums recursivly
remove nums[i] from the permutation set, and try the next possible index
Code
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> results = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; search(nums, visited, new ArrayList<Integer>(), results); return results; } private void search(int[] nums, boolean[] visited, List<Integer> permutation, List<List<Integer>> results) { if (permutation.size() == nums.length) { results.add(new ArrayList<Integer>(permutation)); return; } for (int i = 0; i < nums.length; i++) { if (!visited[i]) { permutation.add(nums[i]); visited[i] = true; search(nums, visited, permutation, results); visited[i] = false; permutation.remove(permutation.size() - 1); } } } }
- Time: O(n! * n) as we have to iterate all the possible permutation for an array. Making a copy of permutation list requires O(n) as well.
- Space: O(n). We need an array to keep track of all the visited numbers. The recursion calls could go as deep as the size of array.
Similar problem:
- Subsets
- Subsets II
- Permutations II
These all all backtracking problems and can be solved with similar code structures.
这篇关于Permutations的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-22项目:远程温湿度检测系统
- 2024-12-21《鸿蒙HarmonyOS应用开发从入门到精通(第2版)》简介
- 2024-12-21后台管理系统开发教程:新手入门全指南
- 2024-12-21后台开发教程:新手入门及实战指南
- 2024-12-21后台综合解决方案教程:新手入门指南
- 2024-12-21接口模块封装教程:新手必备指南
- 2024-12-21请求动作封装教程:新手必看指南
- 2024-12-21RBAC的权限教程:从入门到实践
- 2024-12-21登录鉴权实战:新手入门教程
- 2024-12-21动态权限实战入门指南