关于java:LeetCode046全排列

4次阅读

共计 1077 个字符,预计需要花费 3 分钟才能阅读完成。

全排列

题目形容:给定一个不含反复数字的数组 nums,返回其 所有可能的全排列。你能够 按任意程序 返回答案。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:暴力破解法

用一个队列 temp 记录暂存的后果,每次遍历从队列中取出一个后果,而后往 list 中增加一个 nums 中的元素,其中要判断要增加的元素是否曾经存在,如果存在,则反复了,不增加;如果不存在,则增加到队列中作为其中一个可能的后果。直到所有的 list 中的元素个数都是 nums.length,返回所有的后果。

import java.util.*;

public class LeetCode_046 {public static List<List<Integer>> permute(int[] nums) {List<List<Integer>> result = new ArrayList<>();
        int count = 0;
        List<Integer> list = new ArrayList<>();
        Queue<List<Integer>> temp = new LinkedList<>();
        temp.add(list);
        while (count < nums.length) {int times = temp.size();
            while (times > 0) {List<Integer> cur = temp.poll();
                for (int num : nums) {List<Integer> next = new ArrayList<Integer>(Arrays.asList(new Integer[cur.size()]));
                    Collections.copy(next, cur);
                    if (!next.contains(num)) {next.add(num);
                        temp.add(next);
                    }
                }
                times--;
            }
            count++;
        }
        result.addAll(temp);
        return result;
    }

    public static void main(String[] args) {int[] nums = new int[]{1, 2};
        for (List<Integer> integers : permute(nums)) {for (Integer integer : integers) {System.out.print(integer + " ");
            }
            System.out.println();}
    }
}

【每日寄语】 每天醒来将微笑别在衣襟就会遇见更多的美妙。

正文完
 0