377 Combination Sum IV

Solution (TLE)

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int res = 0;
        for ( int i = 0; i <= n-1; i++ ) {
            if ( nums[i] > target ) return res;
            if ( nums[i] == target ) return res+1;
            res += combinationSum4(nums, target - nums[i]);
        }
        return res;
    }
};

Solution
similar to "coin change!"

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> res(target+1, 0);
        res[0] = 1;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for ( int i = 0; i < target; i++ ) {
            if ( res[i] == 0 ) continue;
            for ( int j = 0; j < n; j++ ) {
                if ( i + nums[j] > target ) break;
                res[i+nums[j]] += res[i];
            }
        }
        return res[target];
    }
};

results matching ""

    No results matching ""