程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> [LeetCode] Combination Sum

[LeetCode] Combination Sum

編輯:關於C++

 

Combination Sum

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

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

     

    For example, given candidate set 2,3,6,7 and target 7,
    A solution set is:
    [7]
    [2, 2, 3]

解題思路:

這道題的題意是從n個正整數中選出值為特定值的所有元素,這n個數中每個數可以重復選用。

這是一個np難問題,暴力法。主要是通過回溯暴力。代碼如下:

 

class Solution {
public:
    vector> combinationSum(vector& candidates, int target) {
        vector> result;
        int len=candidates.size();
        if(len==0){
            return result;
        }
        std:sort(candidates.begin(), candidates.end());
        map keyToNumber;  //相當於系數,表示每個數出現了多少次
        getResult(result, candidates, 0, keyToNumber, target);
    }
    
    void getResult(vector>& result, vector& uniqueCandidates, int candidateIndex, map& keyToNumber, int left){
        if(left<0){
            return;
        }
        if(left==0){
            vector item;
            for(map::iterator it=keyToNumber.begin(); it!=keyToNumber.end(); it++){
                int number=it->second;
                int key = it->first;
                for(int i=0; i=uniqueCandidates.size()){
            return;
        }
        int number=0;
        while(left>=0){
            if(number!=0)
                keyToNumber[uniqueCandidates[candidateIndex]]=number;
            getResult(result, uniqueCandidates, candidateIndex+1, keyToNumber, left);
            if(number!=0){
                keyToNumber.erase(uniqueCandidates[candidateIndex]);
            }
            left = left-uniqueCandidates[candidateIndex];
            number++;
        }
    }
};


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved