字符串算法——数组或字符串全排列(Permutations)
来源:互联网 发布:学安卓软件开发教程 编辑:程序博客网 时间:2024/06/01 16:47
问题:
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]]
这里无重复字符元素
解决思路:可以使用递归的方法来解决该问题,不断对元素进行位置交换
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); dfs(res,nums,0);//递归函数 return res; } // private void dfs(List<List<Integer>> res,int []nums,int j){ if(j==nums.length){ List<Integer>temp = new ArrayList<>();//存储每一次交换后的序列 for(int num:nums)temp.add(num); res.add(temp); } //索引位置递归交换 for(int i = j;i<nums.length;i++){ swap(nums,i,j); dfs(res,nums,j+1); swap(nums,i,j); } } //交换函数 private void swap(int[]nums,int m,int n){ int temp = nums[m]; nums[m]= nums[n]; nums[n] = temp; }}
思路二:采用非递归的方法,可以使用插入法
例如:数组为[1,2,3],先取第一个元素1,然后取得第二个元素进行插入得到[1,2]或者[2,1],再对其插入可以得到[3,1,2]、[1,3,2]、[1,2,3]、[3,2,1]、[2,3,1]、[2,1,3]
class Solution { public List<List<Integer>>permute1(int []nums){ List<List<Integer>> res = new ArrayList<>();//存储全排列后数组 ArrayList<Integer> first = new ArrayList<>(); first.add(nums[0]);//存储首位置元素 res.add(first);//存放第一个列表对象 for(int i= 1;i<nums.length;i++){ List<List<Integer>> newRes = new ArrayList<>();//存放每次插入新值的列表对象 for(List<Integer> temp:res){//待插入新值得序列对象 int size = temp.size()+1; for(int j = 0;j<size;j++){ List <Integer>item = new ArrayList<>(temp);//暂存待插入的序列对象 item.add(j,nums[i]);//插入新值 newRes.add(item);//更新 } } res = newRes; } return res; }}
阅读全文
0 0
- 字符串算法——数组或字符串全排列(Permutations)
- 字符串算法——有重复字符的数组或字符串全排列(Permutations II)
- 数组全排列算法(一)字符串数组全排列——逐个追加组合算法
- LeetCode—**字符串中数字的全排列问题Permutations
- 字符串全排列算法
- 字符串全排列算法
- 字符串全排列算法
- 字符串全排列算法
- 算法---字符串全排列
- 算法---字符串全排列
- 字符串全排列算法
- 字符串全排列算法
- 字符串全排列算法
- 字符串全排列算法
- 字符串数组的全排列——数组
- 字符串或数组全排列的三种方法
- 字符串的全排列算法
- 字符串全排列生成算法
- location.hash 与location.href
- mybatis #传值 与$传值区别
- centos7 移动mysql5.7.19 数据存储位置
- lstrcmp
- js 数组 自定义排序
- 字符串算法——数组或字符串全排列(Permutations)
- 优秀工程师之—UISegmentedControl
- Java代码的执行顺序
- iOS 代码规范~关闭警告
- 【解决方法】未申明的标识符,查找定义时出现解析多义性
- 你的PagedLOD 为什么没有卸载?
- 文件系统读写--文件预读 和 文件锁
- scrapy 官方文档(入门必备)
- 运维之思科篇 -----6.思科项目练习