您的位置:首页 > 其它

[Leetcode]Permutations and Permuations II

2014-11-07 12:26 429 查看
Permutations

Given a collection of numbers, return all possible permutations.

For example,

[1,2,3]
have the following permutations:

[1,2,3]
,
[1,3,2]
,
[2,1,3]
,
[2,3,1]
,
[3,1,2]
,
and
[3,2,1]
.

这是一道最典型得backtracking题目,可以用dfs解决。每次遍历一位得时候,记录该位已经被访问过了,当发现不满足的情况或者达到需要解返回的情况,导致backtracking之后,再次开放该位的修改权限。代码胜过语言描述。

public List<List<Integer>> permute(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (num == null) {
return res;
}

List<Integer> item = new ArrayList<Integer>();
boolean[] visited = new boolean[num.length];
helper(num, res, item, visited);
return res;
}

private void helper(int[] num, List<List<Integer>> res, List<Integer> item, boolean[] visited) {
if (item.size() == num.length) {
res.add(new ArrayList<Integer>(item));
return;
}

for (int i = 0; i < num.length; i++) {
if (!visited[i]) {
item.add(num[i]);
visited[i] = true;
helper(num, res, item, visited);
visited[i] = false;
item.remove(item.size() - 1);
}
}
}


Permutations II

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]
,
and
[2,1,1]
.

相对于I,这个问题多了duplicate,最简单的方法就是先进行排序,然后再遍历。遍历遇到相同的元素,跳过即可。代码相对于上一段代码仅仅多了排序和一个while循环用来去重。

public List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
int n = num.length;
if (n == 0) {
return res;
}
List<Integer> item = new ArrayList<Integer>();
Arrays.sort(num);
boolean[] visited = new boolean
;

helper(res, item, num, visited);
return res;
}

public void helper(List<List<Integer>> res, List<Integer> item, int[] num, boolean[] visited) {
if (item.size() == num.length) {
res.add(new ArrayList<Integer>(item));
return;
}
for (int i = 0; i < num.length; i++) {
if(!visited[i]) {
item.add(num[i]);
visited[i] = true;
helper(res, item, num, visited);
visited[i] = false;
item.remove(item.size() - 1);
while (i+1 < num.length && num[i+1] == num[i]) {
i++;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: