LeetCode40. Combination Sum II

LeetCode40. Combination Sum II

題目:

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
題意分析:這道題和LeetCode39題差不多,也是選擇用回溯的方法去做,但是這道題是不允許重複使用的,所以就多了一點點處理的歩奏。
void isok(vector<int>& candidates, vector<vector<int>>& result, int target, int begin, vector<int> tmp) {
	if (target == 0) {
		result.push_back(tmp);
	}
	else {
		for (int i = begin; i < candidates.size(); i++) {
			if (candidates[i] > target) {
				break;
			}
			if (i == begin || candidates[i] != candidates[i - 1]) {
				tmp.push_back(candidates[i]);
				isok(candidates, result, target - candidates[i], i + 1, tmp);
				tmp.pop_back();
			}
		}
	}
}

代碼:
class Solution {
public:
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		sort(candidates.begin(), candidates.end());
		vector<vector<int>> result;
		vector<int> tmp;
		isok(candidates, result, target, 0, tmp);
		return result;
	}

	void isok(vector<int>& candidates, vector<vector<int>>& result, int target, int begin, vector<int> tmp) {
		if (target == 0) {
			result.push_back(tmp);
		}
		else {
			for (int i = begin; i < candidates.size(); i++) {
				if (candidates[i] > target) {
					break;
				}
				if (i == begin || candidates[i] != candidates[i - 1]) {
					tmp.push_back(candidates[i]);
					isok(candidates, result, target - candidates[i], i + 1, tmp);
					tmp.pop_back();
				}
			}
		}
	}
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章