本文主要是介绍Java | Leetcode Java题解之第46题全排列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {public List<List<Integer>> permute(int[] nums) {List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> output = new ArrayList<Integer>();for (int num : nums) {output.add(num);}int n = nums.length;backtrack(n, output, res, 0);return res;}public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {// 所有数都填完了if (first == n) {res.add(new ArrayList<Integer>(output));}for (int i = first; i < n; i++) {// 动态维护数组Collections.swap(output, first, i);// 继续递归填下一个数backtrack(n, output, res, first + 1);// 撤销操作Collections.swap(output, first, i);}}
}
这篇关于Java | Leetcode Java题解之第46题全排列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!