Leetcode: Permutations 理解分析
来源:互联网 发布:金砖国家成立意义知乎 编辑:程序博客网 时间:2024/06/04 17:56
题目大意: 给定一个整型数组,求出该数组中数字的全排列。
理解:1)本题中给出的数组中没有重复的数字,求出数组的全排列。如[1, 2, 3] 的全排列包括:[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]。
2)采用递归的方式解决本问题。递归在返回到某一个状态时,其状态应与出去时的一致,所以在返回时,记住要恢复状态。用一个hash[]来表示某个数字是否出现过,为0则没有出现过,为1则出现过。当处理过某个数后,即加入ArrayList,就将其hash值置1,在返回时,将加入的数字移除,并同时将其hash值重新置为0,恢复状态。
实现:
public class Solution { private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); private int len = 0; private ArrayList<Integer> arr = new ArrayList<Integer>(); private int[] hash;// 记录是否出现过 public void func(int[] s, int pos) { if(pos == len) { ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int i = 0; i < arr.size(); i ++) { tmp.add(arr.get(i)); } res.add(tmp); return; } for(int i = 0; i < len; i ++) { if(hash[i] == 0) { arr.add(s[i]); hash[i] = 1; // 出现过,置1 func(s, pos + 1); arr.remove(arr.size() - 1); //恢复过程,移除加入的数字; hash[i] = 0; // 将其hash值重新置为0。 } } } public ArrayList<ArrayList<Integer>> permute(int[] num) { if(num == null || num.length == 0) return res; len = num.length; if(len == 1) { arr.add(num[0]); res.add(arr); return res; } hash = new int[len]; for(int i = 0; i < len; i ++) hash[i] = 0; func(num, 0); return res; }}
0 0
- Leetcode: Permutations 理解分析
- Leetcode: Permutations II 理解分析
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- poj 1575 Easier Done Than Said?【字符串处理】
- KMP算法(uva 1328)
- 项目进阶 之 集群环境搭建(一)概述
- poj 3420 Quad Tiling(状态压缩矩阵递推)
- Subsets -- LeetCode
- Leetcode: Permutations 理解分析
- 黑马程序员_.NET字符串
- 黑马程序员 ----- Java基础 之 IO 基本规律总结 Day05
- Container With Most Water
- Regular Expression Matching
- IIS架设网站的问题
- JSP页面静态化总结之一使用URLRewrite实现url地址伪静态化
- 第7周作业1——JMF(Java多媒体框架)的应用之MP3播放器
- BZOJ KMP+矩阵快速幂 1009: [HNOI2008]GT考试