Leetcode - 39. Combination Sum

숲사람·2022년 8월 10일
0

멘타트 훈련

목록 보기
119/237

문제

주어진 값들을 더해서(중복선택 가능) target이 되는 조합을 구하라. 결과 조합이 중복될 수 없다. ([2,2,3]과 [3,2,2]는 동일)

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

해결

백트래킹 문제. 잘 몰랐던것.

  • tmp임시 벡터를 어떻게 선언해야하는지
  • 재귀 호출 직전에 현재값을 push_back()하고, 호출이 끝나면 pop_back()을 해야함.
  • 결과 조합이 중복되지 않기 위해서는 i를 curr부터 시작하야함.
    아래와같이 하면 위 예제의 결과는[[2,2,3],[2,3,2],[3,2,2],[7]]이 나오게된다.
    for (int i = 0; i < candidates.size(); i++)
class Solution {
    vector<vector<int>> ret;
    vector<int> tmp;
    void back_tracking(vector<int> &candidates, int target, int curr)
    {
        if (target < 0) return;
        if (target == 0) {
            ret.push_back(tmp);
            return;
        }
        for (int i = curr; i < candidates.size(); i++) {
            tmp.push_back(candidates[i]);
            back_tracking(candidates, target - candidates[i], i);
            tmp.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        back_tracking(candidates, target, 0);
        return ret;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글