• LeetCode-046-全排列


    全排列

    题目描述:给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/permutations/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:暴力破解法

    用一个队列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();
            }
        }
    }
    

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

  • 相关阅读:
    Laravel 中查询 where 记录
    eclipse svn重定位(relocate)
    使用git ftp发布我个人的hexo博客内容
    oracle数据库查询常用语句
    telnet关闭tomcat
    XML字符串解析成对象的时候应注意空格
    去除焦点边框线
    如何查看和更改mysql数据库文件存放位置
    设置div,td失去焦点
    (加减乘除)字符串计算机
  • 原文地址:https://www.cnblogs.com/kaesar/p/15361436.html
Copyright © 2020-2023  润新知