leetcode 46. Permutations
2017-06-14 23:49
369 查看
Given a collection of distinct numbers, return all possible permutations.
For example,
Subscribe to see which companies asked this question.
全排列问题,复杂度是n!所以就按简单的两两交换作为新组合加入list即可。
public class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>>ans = new ArrayList<List<Integer>>();
if(len==0)return ans;
dfs(0,nums,ans);
return ans;
}
public void swap(int[]nums,int i,int j){
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
public void dfs(int begin,int[]a,List<List<Integer>>ans){
List<Integer> list = new ArrayList<Integer>();
int n = a.length, tmp;
if (begin == n) {
for (int i = 0; i < n; i++)
list.add(a[i]);
ans.add(list);
} else {
for (int i = begin; i < n; i++) {
swap(a,begin,i);
dfs( begin + 1,a, ans);
swap(a,begin,i);
}
}
}
}
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] ]
Subscribe to see which companies asked this question.
全排列问题,复杂度是n!所以就按简单的两两交换作为新组合加入list即可。
public class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>>ans = new ArrayList<List<Integer>>();
if(len==0)return ans;
dfs(0,nums,ans);
return ans;
}
public void swap(int[]nums,int i,int j){
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
public void dfs(int begin,int[]a,List<List<Integer>>ans){
List<Integer> list = new ArrayList<Integer>();
int n = a.length, tmp;
if (begin == n) {
for (int i = 0; i < n; i++)
list.add(a[i]);
ans.add(list);
} else {
for (int i = begin; i < n; i++) {
swap(a,begin,i);
dfs( begin + 1,a, ans);
swap(a,begin,i);
}
}
}
}
相关文章推荐
- [LeetCode-Java]46. Permutations
- leetcode 46. Permutations
- <LeetCode OJ> 46. Permutations
- [LeetCode] 46. Permutations
- LeetCode 46. Permutations
- LeetCode 46. Permutations
- [LeetCode]46. Permutations &&深搜DFS
- LeetCode 46. Permutations
- Leetcode 46. Permutations & 47. Permutations II
- LeetCode笔记:46. Permutations
- [leetcode]46. Permutations
- leetcode_middle_37_46. Permutations
- LeetCode 43.Multiply Strings & 46.Permutations & 47.Permutations II
- leetcode 46. Permutations
- LeetCode-----46.Permutations&&47.Permutations II (全排列----回溯法)
- LeetCode 46. Permutations
- LeetCode - 46. Permutations
- LeetCode 46. Permutations
- Leetcode 46. Permutations
- leetcode 46. Permutations