您的位置:首页 > 其它

leetcode 46. Permutations

2017-06-14 23:49 369 查看
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]
]


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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: