您的位置:首页 > 其它

leetcode-47. Permutations II(重复元素全排列)

2017-05-19 21:59 453 查看
https://leetcode.com/problems/permutations-ii/#/description

问题描述:

含有重复元素的全排列

思路解析:

参考http://blog.csdn.net/u013275928/article/details/72510351

这次考虑了重复元素,新增了一个用来表示该元素是否已经加入到了tempList中的boolean数组,若为真则已经存在,否则加入到templist中。另外,还需要考虑一点,由于先对数组进行排序,相同的值相邻,如果前面的值未加入到templist中,不可以先加入后面的值。

代码如下:

public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {

Arrays.sort(nums);

List<List<Integer>> result=new ArrayList<>();

boolean[] used=new boolean[nums.length];

getDupPer(result,new ArrayList<>(),nums,used);

return result;

}

public void getDupPer(List<List<Integer>> result,List<Integer> temp,int[] nums,boolean[] used)
{
if(temp.size()==nums.length)
{
result.add(new ArrayList<>(temp));
}else
{

for(int i=0;i<nums.length;i++)
{
if( used[i] )continue;
if (i>0 && nums[i-1]==nums[i] && !used[i-1]) continue;

used[i]=true;
temp.add(nums[i]);
getDupPer(result,temp,nums,used);
used[i]=false;
temp.remove(temp.size()-1);

}

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode