384. Shuffle an Array(java,数组全排列,然后随机取)

时间:2023-03-08 23:45:32
384. Shuffle an Array(java,数组全排列,然后随机取)

题目:

Shuffle a set of numbers without duplicates.

分析:

对一组不包含重复元素的数组进行随机重排,reset方法返回最原始的数组,shuffle方法随机返回数组的一个排列,

并且使得获得数组每一个排列的概率都是相同的。为此,可以在初始化时,求出数组的所有排列。在使用shuffle方法时,随机返回全排列中的一个。

代码:

public class Solution {

    //存储数组的所有排列
List<int[]> list = new ArrayList<int[]>();
public Solution(int[] nums) {
//首先求所有排列
permutations(nums,list,0);
} /** Resets the array to its original configuration and return it. */
public int[] reset() {
return list.get(0);
} /** Returns a random shuffling of the array. */
public int[] shuffle() {
int index = (int)(Math.random() * list.size());
return list.get(index);
}
//求数组的所有排列
public void permutations(int[] array,List<int[]> list,int start){
if(array == null){
return;
}
if(start == array.length){
int[] temp = new int[array.length];
System.arraycopy(array,0,temp,0,array.length);
list.add(temp);
}
for(int i = start; i < array.length; ++i){
swap(array,i,start);
permutations(array,list,start+1);
swap(array,i,start);
}
}
//交换元素
public void swap(int[] array,int i,int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
} /**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/