Leetcode: Permutations 理解分析
2014-04-22 08:18
337 查看
题目大意: 给定一个整型数组,求出该数组中数字的全排列。
理解: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,恢复状态。
实现:
理解: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; } }
相关文章推荐
- Leetcode: Two Sum 理解分析
- Leetcode: Longest Consecutive Sequence 理解分析
- Leetcode: LRU Cache 理解分析
- Leetcode: Path Sum 理解分析
- Leetcode: Binary Tree Level Order Traversal II 理解分析
- Leetcode: Max Points on a Line 分析理解
- LeetCode Generate Parentheses 深度分析理解
- Leetcode: Remove Duplicates from Sorted Array II 理解分析
- Leetcode: Minimum Depth of Binary Tree 理解分析
- 算法分析与设计课程(3):【leetcode】Permutations
- Leetcode: Subsets II 理解分析
- Leetcode: Search in Rotate Sorted Array II 理解分析
- Leetcode: Binary Tree Zigzag Level Order Traversal 理解分析
- Leetcode: Copy List With Random Pointer分析理解
- Leetcode: Path Sum II 理解分析
- Leetcode: Maximum Subarray 理解分析
- Leetcode Linked List Cycle II 理解分析
- Leetcode: Remove Duplicates from Sorted Array 理解分析
- Leetcode: Add Binary 理解分析
- Leetcode: String to Integer (atoi) 理解分析