Leet Code 46 Permutations - 排列 - Java
2016-06-22 00:00
393 查看
摘要: Leet Code 46 Permutations - 排列 - Java
问题原始链接 https://leetcode.com/problems/permutations
给定一个由不同数组成的集合,返回所有可能的排列。
例如,[1,2,3] 有以下排列。
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
问题原始链接 https://leetcode.com/problems/permutations
给定一个由不同数组成的集合,返回所有可能的排列。
例如,[1,2,3] 有以下排列。
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
public class Solution { public static List<List<Integer>> permute(int[] nums) { if (nums == null || nums.length == 0) { return new ArrayList<List<Integer>>(); } List<List<Integer>> result = new ArrayList<List<Integer>>(); p(nums, 0, result); return result; } private static void p(int[] a, int i, List<List<Integer>> result) { if (i == a.length - 1) { result.add(toList(a)); return; } p(a, i + 1, result); for (int j = i + 1; j < a.length; j++) { swap(a, i, j); p(a, i + 1, result); swap(a, i, j); } } private static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private static List<Integer> toList(int[] a) { List<Integer> result = new ArrayList<Integer>(a.length); for (Integer i : a) { result.add(i); } return result; } }
相关文章推荐
- JavaScript数组随机排列实现随机洗牌功能
- C#实现排列组合算法完整实例
- php通过排列组合实现1到9数字相加都等于20的方法
- C语言实现的阶乘,排列和组合实例
- C语言实现输入一个字符串后打印出该字符串中字符的所有排列
- python以环状形式组合排列图片并输出的方法
- python标准算法实现数组全排列的方法
- python常规方法实现数组的全排列
- JavaScript实现数字数组按照倒序排列的方法
- JavaScript实现数字数组正序排列的方法
- python回溯法实现数组全排列输出实例分析
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- leetcode561 Array Partition I