1.自己
就是使用深搜.深搜很多用处,包括后面的什么子数组最大和等等。
1047ms
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> permute(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
List<Integer> item = new ArrayList<>();
if (nums == null || nums.length == 0) {
result.add(item);
return result;
}
int[] book = new int[nums.length];
dfs(nums, book, 0, item, result);
return result;
}
public void dfs(int[] nums, int[] book, int step, List<Integer> item, List<List<Integer>> result) {
if (step == book.length) {
result.add(new ArrayList<>(item));
return;
}
for (int i = 0; i < book.length; i++) {
if (book[i] == 0) {
book[i] = 1;
item.add(nums[i]);
dfs(nums, book, step + 1, item, result);
item.remove(item.size() - 1);
book[i] = 0;
}
}
}
public void print(List<List<Integer>> result) {
for (List<Integer> list : result) {
for (Integer i : list) {
System.out.print(i + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = new int[]{2, 1};
List<List<Integer>> result = solution.permute(nums);
solution.print(result);
}
}
2.九章
居然是2409ms.难道是?好像是说的使用contain比较耗时。
使用了list的contain方法就没有使用标记数组,还是比较方便
public class Solution {
public List<List<Integer>> permute(int[] nums) {
ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>();
if (nums == null) {
return rst;
}
if (nums.length == 0) {
rst.add(new ArrayList<Integer>());
return rst;
}
ArrayList<Integer> list = new ArrayList<Integer>();
helper(rst, list, nums);
return rst;
}
public void helper(ArrayList<List<Integer>> rst, ArrayList<Integer> list, int[] nums){
if(list.size() == nums.length) {
rst.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++){
if(list.contains(nums[i])){
continue;
}
list.add(nums[i]);
helper(rst, list, nums);
list.remove(list.size() - 1);
}
}