1 Star 0 Fork 0

Byte/algorithm

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
array_2.java 1.73 KB
一键复制 编辑 原始数据 按行查看 历史
Byte 提交于 2026-07-03 06:34 +08:00 . 11
package arrays;
import java.util.*;
/**
* 题目: 求一个无重复元素数组里面的所有排列组合
* y:[0,1,2]
* 0 1 2
* 0 2 1
* 1 0 2
* 1 2 0
* 2 1 0
* 2 0 1
* @Author Gavin
* @date 2021.12.09 21:16
*/
public class array_2 {
public static List<List<Integer>> solution(int[] arrays){
if(arrays==null||arrays.length==0)return new ArrayList<>();
List<List<Integer>> result=new ArrayList<>();
List<Integer> nums=new ArrayList<>();
for (int pre:arrays)nums.add(pre);
rec(nums,0,result);
//todo 如果是重复元素,则需要去重,利用HashSet,linkedHashSet或者stream的distinct
/* List<List<Integer>> distinctList = new ArrayList<>(new LinkedHashSet<>(originalList));
List<List<Integer>> distinctList = originalList.stream()
.distinct()
.collect(Collectors.toList());*/
return result;
}
//递归调用
private static void rec(List<Integer> nums,int start,List<List<Integer>> result){
if(start==nums.size()){
result.add(new ArrayList<>(nums));
}else{
for (int i=start;i<nums.size();++i){
Collections.swap(nums,i,start);
//这里需要好好理解,当start和某个元素交换之后,那么从下一个元素开始又可以当成一个新的数组来进行递归处理了
//当然前提是需要该数组是无重复的元素,否则交换之后可能会出现重复
rec(nums,start+1,result);
Collections.swap(nums,i,start);
}
}
}
public static void main(String[] args) {
int[] arr={0,1,2,2};
System.out.println(solution(arr).size());
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Gavery/algorithm.git
git@gitee.com:Gavery/algorithm.git
Gavery
algorithm
algorithm
master

搜索帮助