您的位置:首页 > 编程语言 > Java开发

[leetcode]46. Permutations@Java解题报告

2017-08-19 10:34 483 查看
https://leetcode.com/problems/permutations/description/

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]
]


package go.jacob.day819;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* 46. Permutations
* @author Jacob
* 题意:求数组的全排列
*/
public class Demo1 {
List<List<Integer>> res;

public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 1)
return res;
//对数组元素进行从小到大排序
Arrays.sort(nums);
ArrayList<Integer> list = new ArrayList<Integer>();

solve(list, nums);

return res;
}

private void solve(ArrayList<Integer> list, int[] nums) {
if (list.size() == nums.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (!list.contains(nums[i])) {
list.add(nums[i]);
solve(list, nums);
list.remove(list.size() - 1);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: