47. Permutations II

来源:互联网 发布:intouch组态软件下载 编辑:程序博客网 时间:2024/05/19 19:14

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[  [1,1,2],  [1,2,1],  [2,1,1]]

思路:
还是DFS,不过有重复,那重点就是去重了。同样深度的情况下,出现重复的,那么需要跳过。
具体说就是:判断是否和上一个相等,相等的情况下如果上一个没用过,说明是上一个回溯结束的,同一层,那么就不要再重新来一轮了,跳过。 112 分别以1,1,2开始,第二个1和第一个1开始的结果重复的。在第一个1开始的时候,下一层的当前元素是第二个1,虽然也是1,但是上一个1被用了,说明它是不同深度的,所以不跳过。

class Solution {    public List<List<Integer>> permuteUnique(int[] nums) {        List<List<Integer>> res = new ArrayList<>();        boolean[] visited = new boolean[nums.length];        Arrays.sort(nums);        dfs(res, visited, nums, new ArrayList<>());        return res;    }    public void dfs(List<List<Integer>> res, boolean[] visited, int[] nums, List<Integer> tempList) {        if (tempList.size() == nums.length) {            res.add(tempList);        } else {            for (int i = 0; i < nums.length; i++) {                if (i != 0 && nums[i] == nums[i-1] && !visited[i-1])                     continue;                if (!visited[i]) {                    visited[i] = true;                    tempList.add(nums[i]);                    dfs(res, visited, nums, new ArrayList<>(tempList));                    tempList.remove(tempList.size() - 1);                    visited[i] = false;                }                }        }    }}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 诚能见可欲则思知足以自戒 思妇病母 思母葡萄糖酸钙锌口服溶液 思母 英思派 思派 思涵 快穿之悲惨人生系统 思镜渠 思漩 思潮起伏 思潮 思潮什么 昆明新思潮酒店 四会新思潮酒店 思然 蠢然思动 思然聚乙二醇滴眼液 思然聚乙二醇滴眼液价格 思然眼药水 思然滴眼液 思然 聚乙二醇滴眼液 聚乙二醇滴眼液价格 聚乙二醇滴眼液 思琦 思琪 ts思琪 思琪名字的含义 白笑笑生思琪的烧烤 思琳 过肩龙纹身讲究和忌讳 纹身衣 思瑞 思瑞全集 思瑞在线 思瑞缺钱 思瑞姐 思瑞主播 思瑞整形 思瑞黑色蕾丝58分钟 美乳女神思瑞 网络红人思瑞