全排列
题目形容:给定一个不含反复数字的数组 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();
}
}
}
【每日寄语】 每天醒来将微笑别在衣襟就会遇见更多的美妙。
发表回复