#The way to brush questions with leetcode 40 combination sum II

Given an array candidates and a target number target, find out all combinations of candidates that can make numbers and targets.Each number in candida...

Given an array candidates and a target number target, find out all combinations of candidates that can make numbers and targets.
Each number in candidates can only be used once in each combination.
Explain:
All numbers, including the target number, are positive integers.
A solution set cannot contain duplicate combinations.

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

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

That is to say 39 questions Add one to avoid repetition:

#include <iostream> #include <vector> #include <algorithm> using namespace std; static int i=0; void recurrent(vector<int>& candidates,int target,int addr,vector<vector<int>>& ans,vector<int>& temp)//addr Is the current traversal position, { if(target==0) { // if(temp.size()==1) // cout<<temp[0]<<endl; // if(temp.size()==3) // cout<<temp[0]<<temp[1]<<temp[2]<<endl; if(find(ans.begin(),ans.end(),temp)==ans.end()) ans.push_back(temp);//Avoid duplication return; } if(target<0) return; for(int i=addr;i<candidates.size();i++) { target-=candidates[i]; temp.push_back(candidates[i]); recurrent(candidates,target,i+1,ans,temp); temp.pop_back();//Restore to continue traversal target+=candidates[i]; } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> ans; int count=candidates.size(); if(count==0||target<0) return ans; vector<int> temp; sort(candidates.begin(),candidates.end());//Sort, avoid repetition recurrent(candidates,target,0,ans,temp); return ans; } int main() { vector<int> candidates={2,5,2,1,2}; vector<vector<int>> ans=combinationSum2(candidates,5); std::cout << ans.size()<< std::endl; return 0; }

4 December 2019, 07:01 | Views: 7157

Add new comment

For adding a comment, please log in
or create account

0 comments