/**
* e.g. nums = 1, 2, 3
* bt()
* tmp(1)
* bt()
* tmp(1, 2)
* bt()
* tmp(1, 2, 3)
* bt()
* add(tmp) return
* tmp.remove(2)
* i == 2 end return
* remove(1)
* i == 1 tmp(1, 3)
* bt()
* tmp(1, 3, 2)
* bt()
* add(tmp) return
* ...
*/
public class Solution {
public static void backTrack(int[] nums, List<Integer> tmp, List<List<Integer>> res) {
if (tmp.size() == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
else {
for (int i=0; i<nums.length; i++) {
if (tmp.contains(nums[i])) continue; // time complexity for ArrayList.contains is O(n)
tmp.add(nums[i]);
backTrack(nums, tmp, res);
tmp.remove(tmp.size()-1);
}
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backTrack(nums, new ArrayList<>(), res);
return res;
}
}
07-10
07-10
07-10
07-10
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交