Leetcode 40. Combination Sum II

题目链接
问题描述

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

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

解题思路

本题做法与Leetcode 39类似,使用深度优先搜索,用path向量记录求和的向量,当path向量中的数字和与target相同时就把path保存到要返回的结果vector中,并进行回溯操作。需要注意的是本题的solution set中不含有重复的vector,这样可以先将path保存在set中,最后将set中的数据转到vector并返回该vector即可。代码如下:

class Solution {
public:
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<int> path;
		vector<vector<int> > ret;
		set<vector<int> > myRet;
		if (candidates.size() == 0) return ret;
		sort(candidates.begin(), candidates.end());
		if (target < candidates[0]) return ret;
		helper(candidates, 0, 0, target, path, myRet);
		set<vector<int> >::iterator it;
		for (it = myRet.begin(); it != myRet.end(); it++) {
			ret.push_back(*it);
		}
		
		return ret;
	}

	void helper(vector<int>& candidates, int nowIndex, int nowSum, int target, vector<int>& path, set<vector<int> >& myRet) {
		if (nowSum > target) return;
		if (nowSum == target) {
			myRet.insert(path);
			return;
		}
		for (int i = nowIndex; i < candidates.size(); i++) {
			path.push_back(candidates[i]);
			helper(candidates, i + 1, nowSum + candidates[i], target, path, myRet);
			path.pop_back();
		}
	}
};

另外也可以在helper函数中剔除candidates中的重复元素,代码如下:

class Solution {
public:
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<int> path;
		vector<vector<int> > ret;
		if (candidates.size() == 0) return ret;
		sort(candidates.begin(), candidates.end());
		if (target < candidates[0]) return ret;
		helper(candidates, 0, 0, target, path, ret);
		

		return ret;
	}

	void helper(vector<int>& candidates, int nowIndex, int nowSum, int target, vector<int>& path, vector<vector<int> >& ret) {
		if (nowSum > target) return;
		if (nowSum == target) {
			ret.push_back(path);
			return;
		}
		for (int i = nowIndex; i < candidates.size(); i++) {
			path.push_back(candidates[i]);
			helper(candidates, i + 1, nowSum + candidates[i], target, path, ret);
			path.pop_back();
			while (candidates[i] == candidates[i + 1]) i++;//这里跳过了重复元素
		}
	}
};

猜你喜欢

转载自blog.csdn.net/SYSU_Chan/article/details/80280403