【leetcode】第46题 Permutations(递归法)题目+解析+代码
来源:互联网 发布:天盾苹果手机数据恢复软件 编辑:程序博客网 时间:2024/06/05 09:36
【题目】
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
【解析】
这个题目就是练习全排列的题目,这里用的递归法,非递归法参照47题即可解答。
【代码】
public static List<List<Integer>> permute(int[] nums) { LinkedList<List<Integer>> res = new LinkedList<List<Integer>>(); prem(res,nums,0,nums.length-1); return res; } public static void swap(int[] nums,int p,int q){ int temp=nums[p]; nums[p]=nums[q]; nums[q]=temp; } public static void prem(List<List<Integer>> res,int[] nums,int p,int q){ if(p==q){ List<Integer> tempList = new ArrayList<Integer>(); for(int b:nums) tempList.add(b); res.add(tempList); } else{ for(int i=p;i<nums.length;i++) { swap(nums,p,i); prem(res,nums,p+1,q); swap(nums,p,i); } } }
阅读全文
0 0
- 【leetcode】第46题 Permutations(递归法)题目+解析+代码
- 【leetcode】第47题 Permutations II(非递归法)题目+解析+代码
- 【leetcode】第6题 ZigZag Conversion 题目+解析+代码
- 【leetcode】第14题 Longest Common Prefix 题目+解析+代码
- 【leetcode】第20题 Valid Parentheses 题目+解析+代码
- 【leetcode】第10题 Regular Expression Matching 题目+解析+代码
- 【leetcode】第28题 Implement strStr() 题目+解析+代码
- 【leetcode】第32题 Longest Valid Parentheses 题目+解析+代码
- 【leetcode】第36题 Valid Sudoku 题目+解析+代码
- 【leetcode】第38题 Count and Say 题目+解析+代码
- 【leetcode】第48题 Rotate Image 题目+解析+代码
- 【leetcode】第44题 Wildcard Matching 题目+解析+代码
- 【leetcode】第53题 Maximum Subarray 题目+解析+代码
- 【leetcode】第54题 Spiral Matrix 题目+解析+代码
- 【leetcode】第55题 Jump Game 题目+解析+代码
- 【leetcode】第56题 Merge Intervals 题目+解析+代码
- 【leetcode】第59题 Spiral Matrix II 题目+解析+代码
- 【leetcode】第62题 Unique Paths 题目+解析+JAVA代码
- ExoPlayer Talk 01 缓存策略分析与优化
- memcache、redis原理对比
- 深度学习网络调参技巧_02
- 在Qt 5.9.1通过qt.conf指定共享库路径部署应用程序
- map函数,key相同的value存在list里,对dic进行排序
- 【leetcode】第46题 Permutations(递归法)题目+解析+代码
- 算法竞赛入门经典 下落的树叶
- 三个关于字符串的考点
- dubbo配置文件xml校验报错
- 【算法】热度排行算法
- SpringMVC日期类型转换问题三大处理方法归纳
- Java中对象的强、软、弱、虚引用
- 深度学习网络训练技巧汇总
- RSTP对比STP端口状态