1 Star 0 Fork 0

临窗旋墨 / basics

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
J0046_M_Permute.java 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
临窗旋墨 提交于 2020-12-11 08:11 . leetcode :46 全排列 回溯
package pers.vic.basics.leetcode;
import java.util.*;
/**
* @description: 46. 全排列 {@literal https://leetcode-cn.com/problems/permutations/} 回溯
* @author Vic.xu
* @date: 2020/12/9 10:31
*/
public class J0046_M_Permute {
/*
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
*/
/**
* 已经对回溯有所了解,这些的问题应该好解决
*/
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
dfs(nums, res, new ArrayDeque<Integer>(len), new boolean[len], len);
return res;
}
/**
* 把每个位置的的数字罗列出来即可
*/
public static void dfs(int[] nums, List<List<Integer>> res, Deque<Integer> temp, boolean[] used, int len){
if (temp.size() == len) {
res.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < len; i++) {
//当前下标是否已经被使用
if (used[i]){
continue;
}
used[i] = true;
temp.add(nums[i]);
dfs(nums, res, temp, used, len);
//状态恢复
used[i] = false;
temp.removeLast();
}
}
public static void main(String[] args) {
permute(new int[]{1,2,3}).forEach(System.out::println);
}
}
Java
1
https://gitee.com/xuqiudong/basics.git
git@gitee.com:xuqiudong/basics.git
xuqiudong
basics
basics
master

搜索帮助