算法14 Permutations
来源:互联网 发布:iphone铃声助手mac 编辑:程序博客网 时间:2024/05/16 18:15
题目:给出不同的数字的集合,返回所有可能的排列组合。
例如,
[1,2,3] 有如下的排列组合:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:根据题意输入数据中无重复元素。以递归方式找出所有排列。每次循环给出的数组时,判断temp中是否有该元素,当全部都在temp中时,加入list中。
代码:
public static void main(String[] args) throws Exception { int[] num = {1,2,3}; permute(num);}public static List<List<Integer>> permute(int num[]){ List<List<Integer>> list = new ArrayList<List<Integer>>(); backtrack(list,new ArrayList<Integer>(), num); return list;}public static void backtrack(List<List<Integer>> list,List<Integer> temp,int[] num){ if(temp.size()==num.length){ list.add(new ArrayList<Integer>(temp)); }else { for (int i = 0; i < num.length; i++) { //若临时list中有这个值,则结束本次循环继续下个循环 if(temp.contains(num[i])) continue; temp.add(num[i]); backtrack(list,temp,num); temp.remove(temp.size()-1); } }}
阅读全文
0 0
- 算法14 Permutations
- LeetCode算法题目:Permutations
- 每日算法之三十六:Permutations && Permutations II
- LeetCode算法题之Permutations
- 46. Permutations --- leetcode 算法笔记
- Permutations 全排列生成算法
- 算法系列——Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- 用nodejs到底做什么?
- codeforces-894C
- Binary String Matching
- FTP文件传输工具
- 斯坦福大学机器学习笔记——过拟合问题以及正则化的解决方法
- 算法14 Permutations
- 吸引百万用户的“社交实验站”,会孵化出下一个陌陌吗?
- 标准OPC Client(OPC客户端)使用说明
- ArrayList和LinkedList的大致区别
- 前端初始化代码
- DPDK-__attribute__((constructor))
- 手动部署 ceph osd (luminous 版)
- 假的模拟水流动
- osgEarth高程着色图案例 35. contourmap.earth