当前位置:网站首页>Leetcode-046-full permutation

Leetcode-046-full permutation

2021-10-14 05:47:07 Lion, tiger and leopard

Full Permutation

Title Description : Give an array without duplicate numbers nums , Back to its All possible permutations . You can In any order Return to the answer .

Please refer to LeetCode Official website .

source : Power button (LeetCode)
link :https://leetcode-cn.com/probl...
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Solution 1 : brute-force attack
With a queue temp Record the results of temporary storage , One result is taken from the queue each time , Then go to list Add a nums The elements in , To judge whether the element to be added already exists , If there is , Is repeated , Don't add ; If it doesn't exist , Is added to the queue as one of the possible results . Until all list The number of elements in is nums.length, Return all results .
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 】 When you wake up every day, put a smile on your skirt and you will meet more beautiful people .

版权声明
本文为[Lion, tiger and leopard]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211002145413059D.html

随机推荐