題目
46 Permutations
47 Permutations II
31 Next Permutation
784 Letter Case Permutation
78 Subsets
90 Subsets II
2597 The Number of Beautiful Subsets
77 Combinations
39 Combination Sum
40 Combination Sum II
216 Combination Sum III
觀念
組合與排列最大差異,排列是有順序,組合沒有順序,所以排列數通常較大
排列,每個元素都必須包含,所以每次都需要重頭拜訪,需要額外vector
used來紀錄該元素是否拜訪過。當然也可迴圈遍歷find()檢查其值是否已包含,但較費時且也較不泛化。 組合沒有順序性可言,不必重頭拜訪,所以可以事先用排序,在借助vector
used 或 if(i > s && nums[i] == nums[i-1]) continue; 條件語句。 子集,沒有順序性可言,不必重頭拜訪。紀錄拜訪樹的每個路徑,不拜訪錯過的
陣列有重複元素,可以排序,搭配if(i > s && nums[i] == nums[i-1]) continue;,去掉重複元素,或是vector
used,去掉重複元素 78 Subsets
90 Subsets II
784 Letter Case Permutation
DFS
77 Combinations
1 | void traverse(int l, int r, int k, vector<int> &path, vector<vector<int>> &ret){ |
39 Combination Sum
1 | void traverse(int s, vector<int> &candidates, int target, vector<vector<int>>&ret, vector<int> &path){ |
40 Combination Sum II
1 | vector<vector<int>> ret; |
216 Combination Sum III
1 | vector<vector<int>> ret; |
Permutations
46 Permutations
1 | vector<vector<int>> ret; |
47 Permutations II
1 | set<vector<int>> ret; |
31 Next Permutation
1 | void nextPermutation(vector<int>& nums) { |
784 Letter Case Permutation
1 | vector<string> ret; |
Subsets
78 Subsets
1 | vector<vector<int>> ret; |
90 Subsets II
1 |
|
Combinations
77. Combinations
1 | class Solution { |
39. Combination Sum
1 | class Solution { |
40. Combination Sum II
1 | class Solution { |
216. Combination Sum III
1 | class Solution { |