Problem 3 Permutation I母题
Method 1 (只对combination有效)不能不加,只能加,一个一个加
public List<List<Integer>> permutation(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
List<Integer> current = new ArrayList<>();
backTracking(result, nums, current, 0);
return result;
}
// index:当前层我要固定的位置是谁:层数的信息
private void backTracking(List<List<Integer>> result, int[] nums, List<Integer> current, int index) {
if (index == nums.length) {
result.add(new ArrayList<>(current));
return;
}
for (int i = 0; i < nums.length; i++) {
// method 1: O(n) time to check current 里面是不是有nums[i], list: contains(val), O(n)
if (!current.contains(nums[i])) {
current.add(nums[i]);
backTracking(result, nums, current, index + 1);
current.remove(current.size() - 1);
}
}
}Method 2 swap swap
Last updated