2019.6.16 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
全排列问题的标准交换递归解法。详细思路可以参考之前刷过的剑指Offer题:
#数据结构与算法学习笔记#剑指Offer26:字符串的排列升级版 + 去重全排列问题3种解法 + 字典序算法 + 测试用例(Java、C/C++)
Given a collection of distinct integers, return all possible permutations.
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
/**
*
* @author ChopinXBP
* Given a collection of distinct integers, return all possible permutations.
* 给定一个没有重复数字的序列,返回其所有可能的全排列。
*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Permutations {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums = {1, 2, 3};
List<List<Integer>> result = permute(nums);
for(int i = 0; i < result.size(); i++) {
for(int j = 0; j < result.get(i).size(); j++) {
System.out.print(result.get(i).get(j) + " ");
}
System.out.println("");
}
}
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums == null || nums.length == 0) return result;
Solution(nums, 0, result);
return result;
}
public static void Solution(int[] nums, int loc, List<List<Integer>> result) {
if(loc == nums.length) {
//int[]转ArrayList
Integer[] newlist = Arrays.stream(nums).boxed().toArray(Integer[]::new);
result.add(new ArrayList<>(Arrays.asList(newlist)));
}
for(int i = loc; i < nums.length; i++) {
int temp = nums[loc];
nums[loc] = nums[i];
nums[i] = temp;
Solution(nums, loc + 1, result);
temp = nums[loc];
nums[loc] = nums[i];
nums[i] = temp;
}
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#