LeetCode 46 - Permutations
程序员文章站
2024-01-18 09:40:22
...
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]
.
public List<List<Integer>> permute(int[] num) { List<List<Integer>> result = new ArrayList<>(); perm(result, num, 0); return result; } public void perm(List<List<Integer>> result, int[] num, int pos) { if(pos == num.length) { List<Integer> list = new ArrayList<Integer>(); for(int a:num) list.add(a); result.add(list); return; } for(int i=pos; i<num.length; i++) { swap(num, i, pos); perm(result, num, pos+1); swap(num, i, pos); } } private void swap(int[] num, int i, int j) { int tmp = num[i]; num[i] = num[j]; num[j] = tmp; }
推荐阅读
-
LeetCode 46 - Permutations
-
Leetcode 454. 4Sum II
-
[题记]链表的中间节点-leetcode
-
LeetCode 193. Valid Phone Numbers
-
LeetCode-297.Serialize and Deserialize Binary Tree(二叉树的序列化和反序列化)
-
Leetcode---栈系列刷题(python3实现)----#20有效的括号
-
Leetcode题Binary Search: 222/230/240/275/278/300,Python多种解法(十五)
-
LeetCode BinarySearch 702 Search in a Sorted Array of Unknown Size
-
LeetCode BinarySearch 278 first bad version
-
LeetCode_35. Search Insert Position