My code:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> permute(int[] nums) {
if (nums == null || nums.length == 0)
return null;
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
ArrayList<Integer> permutations = new ArrayList<Integer>();
boolean[] isVisited = new boolean[nums.length];
getPermutations(nums, isVisited, permutations, result);
return result;
}
private void getPermutations(int[] nums, boolean[] isVisited, ArrayList<Integer> permutations
, ArrayList<List<Integer>> result) {
if (permutations.size() == nums.length)
result.add(new ArrayList<Integer>(permutations));
else {
for (int i = 0; i < nums.length; i++) {
if (isVisited[i])
continue;
permutations.add(nums[i]);
isVisited[i] = true;
getPermutations(nums, isVisited, permutations, result);
permutations.remove(permutations.size() - 1);
isVisited[i] = false;
}
}
}
public static void main(String[] args) {
Solution test = new Solution();
int[] a = {1, 2, 3};
System.out.println(test.permute(a));
}
}
My test result:
这道题目不是和之前的combinations很像么。为什么没做出来。
combination 是指定了k,但是顺序固定。
这道题目简单些,顺序不固定,但长度固定。所以每一次都可以用for循环遍历。然后设置一个布尔数组,表示那些被访问过哪些没被访问过就行。
**
总结: backtracing
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public List<List<Integer>> permute(int[] nums) {
ArrayList<List<Integer>> ret = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0)
return ret;
ArrayList<Integer> group = new ArrayList<Integer>();
boolean[] isVisited = new boolean[nums.length];
helper(nums.length, nums, isVisited, group, ret);
return ret;
}
private void helper(int k, int[] nums, boolean[] isVisited,
ArrayList<Integer> group, ArrayList<List<Integer>> ret) {
if (k <= 0) {
ret.add(new ArrayList<Integer>(group));
return;
}
else {
for (int i = 0; i < nums.length; i++) {
if (isVisited[i])
continue;
else {
group.add(nums[i]);
isVisited[i] = true;
helper(k - 1, nums, isVisited, group, ret);
isVisited[i] = false;
group.remove(group.size() - 1);
}
}
}
}
}
一开始做的太浮躁,觉得以前做过,也很熟练,就上手开始写,没思考清楚。
切忌,不要上手就写,即使多么熟练。一定要先想清楚整体思路,再开始写!
Anyway, Good luck, Richardo!