Star

LeetCode Backtracking Problems

LeetCode 78: Subsets

Question

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,3], a solution is:

1
2
3
4
5
6
7
8
9
10
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Explanation

回溯递归

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
subsetsHelper(list, new ArrayList<>(),nums, 0);
return list;
}
public void subsetsHelper(List<List<Integer>> list, List<Integer> tmpList, int[] nums, int start) {
System.out.println(tmpList.toString());
list.add(new ArrayList<>(tmpList));
for (int i=start; i<nums.length; i++) {
System.out.println(i);
tmpList.add(nums[i]);
subsetsHelper(list, tmpList, nums, i+1);
tmpList.remove(tmpList.size()-1);
}

LeetCode 90. Subsets II

Question

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,2], a solution is:

1
2
3
4
5
6
7
8
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

Explanation

和上一题一致,只是对于重复的,skip掉。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
subsetsHelper(list, new ArrayList<>(),nums, 0);
return list;
}
public void subsetsHelper(List<List<Integer>> list, List<Integer> tmpList, int[] nums, int start) {
System.out.println(tmpList.toString());
list.add(new ArrayList<>(tmpList));
for (int i=start; i<nums.length; i++) {
if (i != start && nums[i] == nums[i-1] ) continue;
tmpList.add(nums[i]);
subsetsHelper(list, tmpList, nums, i+1);
tmpList.remove(tmpList.size()-1);
}
}

LeeCode 46. Permutations

Question

Given a collection of distinct numbers, return all possible permutations.

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

1
2
3
4
5
6
7
8
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Explanation

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
subsetsHelper(list, new ArrayList<>(),nums);
return list;
}
public void subsetsHelper(List<List<Integer>> list, List<Integer> tmpList, int[] nums) {
if (tmpList.size() == nums.length) {
list.add(new ArrayList<>(tmpList));
}
else {
for (int i= 0; i<nums.length; i++) {
if (tmpList.contains(nums[i])) continue;
tmpList.add(nums[i]);
subsetsHelper(list, tmpList, nums);
tmpList.remove(tmpList.size()-1);
}
}
}