暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

LeetCode-046-全排列

明日之X 2021-10-02
135

全排列

题目描述:给定一个不含重复数字的数组 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();
      }
  }
}

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



文章转载自明日之X,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论