LeetCode-046-全排列
全排列
题目描述:给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:暴力破解法
用一个队列temp记录暂存的结果,每次遍历从队列中取出一个结果,然后往list中添加一个nums中的元素,其中要判断要添加的元素是否已经存在,如果存在,则重复了,不添加;如果不存在,则添加到队列中作为其中一个可能的结果。直到所有的list中的元素个数都是nums.length,返回所有的结果。
import java.util.*;
public class LeetCode_046 {
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int count = 0;
List<Integer> list = new ArrayList<>();
Queue<List<Integer>> temp = new LinkedList<>();
temp.add(list);
while (count < nums.length) {
int times = temp.size();
while (times > 0) {
List<Integer> cur = temp.poll();
for (int num : nums) {
List<Integer> next = new ArrayList<Integer>(Arrays.asList(new Integer[cur.size()]));
Collections.copy(next, cur);
if (!next.contains(num)) {
next.add(num);
temp.add(next);
}
}
times--;
}
count++;
}
result.addAll(temp);
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2};
for (List<Integer> integers : permute(nums)) {
for (Integer integer : integers) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
【每日寄语】 每天醒来将微笑别在衣襟就会遇见更多的美好。
分类:
LeetCode-个人题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了