LeetCode 39. Combination Sum II

和LeetCode 38. Combination Sum类似。


将candidates排升序后去重并用一个cnt数组记录对应数字的个数,再递归求解。


代码:

class Solution 
{
public:
	vector<vector<int> > combinationSum2(vector<int> &candidates, int target) 
	{
		sort(candidates.begin(), candidates.end());
		for (size_t i = 0; i < candidates.size(); ++ i)
		{
			if (i==0 || candidates[i]!=candidates[i-1])
			{
				num.push_back( candidates[i] );
				cnt.push_back( 1 );
			} else
			{
				++ cnt[cnt.size()-1];
			}
		}
		vector<int> now;
		dfs(now, 0, target);
		return ret;
	}
private:
	vector<int> num;
	vector<int> cnt;
	vector<vector<int> > ret;
	void dfs(vector<int>& now, size_t index, int remain)
	{
		for (size_t i = index; i < num.size(); ++ i)
		{
			if (num[i] > remain)
			{
				break;
			} else
			{
				int cur = remain;
				for (int j = 0; j<cnt[i] && num[i]<=cur; ++ j)
				{
					cur -= num[i];
					now.push_back( num[i] );
					dfs(now, i+1, cur);
				}
				if (cur == 0)
				{
					ret.push_back( now );
				}
				while (cur != remain)
				{
					now.pop_back();
					cur += num[i];
				}
			}
		}
	}
};


你可能感兴趣的:(LeetCode,C++)