static void CombinationWithDuplicatedElementsVer2Helper(Array1D &array, int left, int k, int times, Array1D &temp, Array2D &result) { if (array.size() - left < k) { return; } if (k == 0) { result.push_back(temp); return; } for (int i = left; i <= array.size(); i++) { if (i == 0 || array[i] != array[i - 1]) { times = 1; temp.push_back(array[i]); CombinationWithDuplicatedElementsVer2Helper(array, i + 1, k - 1, 1, temp, result); temp.pop_back(); } else { times++; if (temp.size() >= times - 1 && temp[temp.size() - times + 1] == array[i]) { temp.push_back(array[i]); CombinationWithDuplicatedElementsVer2Helper(array, i + 1, k - 1, times, temp, result); temp.pop_back(); } } } }
static void CombinationWithDuplicatedElementsHelper(Array1D &array, int left, int k, int times, Array1D &temp, Array2D &result) { assert(left >= 0); if (array.size() - left < k) { return; } if (k == 0) { result.push_back(temp); return; } if (left == 0 || array[left] != array[left - 1]) { temp.push_back(array[left]); CombinationWithDuplicatedElementsHelper(array, left + 1, k - 1, 1, temp, result); temp.pop_back(); CombinationWithDuplicatedElementsHelper(array, left + 1, k, 1, temp, result); } else { if (temp.size() >= times && temp[temp.size() - times] == array[left]) { temp.push_back(array[left]); CombinationWithDuplicatedElementsHelper(array, left + 1, k - 1, times + 1, temp, result); temp.pop_back(); } CombinationWithDuplicatedElementsHelper(array, left + 1, k, times + 1, temp, result); } }
static void CombinationHelper(Array1D &array, int left, int right, int k, Array1D &temp, Array2D &result) { assert(!array.empty()); assert(left >= 0 && right >= 0); if (right - left + 1 < k) { return; } if (k == 0) { result.push_back(temp); return; } temp.push_back(array[left]); CombinationHelper(array, left + 1, right, k - 1, temp, result); temp.pop_back(); CombinationHelper(array, left + 1, right, k, temp, result); }
static void CombinationVer2Helper(Array1D &array, int left, int right, int k, Array1D &temp, Array2D &result) { assert(!array.empty()); assert(left >= 0 && right >= 0); if (k == 0) { result.push_back(temp); return; } for (int i = left; i <= right - k + 1; i++) { temp.push_back(array[i]); CombinationVer2Helper(array, i + 1, right, k - 1, temp, result); temp.pop_back(); } }