(Java)LeetCode-46. Permutations
2016-09-28 13:11
393 查看
Given a collection of distinct numbers,
return all possible permutations.
For example,
这道题中规中矩吧,全排列没有重复的数组,就用递归即可。代码如下:
public List<List<Integer>> permute(int[] nums) {
boolean[] flags = new boolean[nums.length];
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> empty = new ArrayList<Integer>();
permute(result,empty,nums,flags,0);
return result;
}
private void permute(List<List<Integer>> result,List<Integer> empty,int[] nums, boolean[] flags, int cnt) {
// TODO Auto-generated method stub
if(cnt == nums.length){
result.add(new ArrayList<Integer>(empty));
}
for(int i = 0; i < flags.length; i++){
if(flags[i] == false){
empty.add(nums[i]);
flags[i] = true;
permute(result, empty, nums, flags, cnt+1);
flags[i] = false;
empty.remove(empty.size()-1);
}
}
}
不过在网上看到一个类似的十分巧妙的想法,链接如下:http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51534048 速度十分快
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] ]
这道题中规中矩吧,全排列没有重复的数组,就用递归即可。代码如下:
public List<List<Integer>> permute(int[] nums) {
boolean[] flags = new boolean[nums.length];
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> empty = new ArrayList<Integer>();
permute(result,empty,nums,flags,0);
return result;
}
private void permute(List<List<Integer>> result,List<Integer> empty,int[] nums, boolean[] flags, int cnt) {
// TODO Auto-generated method stub
if(cnt == nums.length){
result.add(new ArrayList<Integer>(empty));
}
for(int i = 0; i < flags.length; i++){
if(flags[i] == false){
empty.add(nums[i]);
flags[i] = true;
permute(result, empty, nums, flags, cnt+1);
flags[i] = false;
empty.remove(empty.size()-1);
}
}
}
不过在网上看到一个类似的十分巧妙的想法,链接如下:http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51534048 速度十分快
相关文章推荐
- leetCode 17. Letter Combinations of a Phone Number 字符串 | 回溯 | Medium
- LeetCode-Sudoku Solver
- backtracking in Date Structures and Algorithm Analysis in C
- [leetCode] Word Search (new start. Let's go this)
- [leetCode] Subsets
- [leetCode] Subsets II
- [leetCode] Combination Sum
- [leetCode] Combination Sum II
- [leetCode] Combination Sum III
- Leetcode#60||Permutation Sequence
- Leetcode#22||Generate Parentheses
- Leetcode#17||Letter Combinations of a Phone Number
- Subsets II
- Combination Sum III
- Letter Combinations of a Phone Number
- [leetcode] Palindrome Partitioning
- [leetcode] restore IP address
- [leetcode] Generate Parenthese
- [leetcode] Letter Combinations of a Phone Number
- 【算法总结】 排列组合问题 - backtracking