1
头图

Full array

Title description: Given an array nums without repeated numbers, return all possible permutations. You can return the answers in any order.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/permutations/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Brute force method
Use a queue temp to record the results of the temporary storage, take out a result from the queue each time traversal, and then add an element in nums to the list, in which it is necessary to determine whether the element to be added already exists, if it exists, repeat it, no Add; if it does not exist, add it to the queue as one of the possible results. Until the number of elements in all lists is nums.length, all results are returned.
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();
        }
    }
}
【Daily Message】 wake up every day, put a smile on the skirt of your clothes and you will meet more beautiful things.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!