Leetcode 77. Combinations 39. Combination Sum

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4], 
]

DFS轻松解决,需要注意的是这个是Combination不是Permutation

vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> result;
    vector<int> curr;
    
    if(n == k){
        result.push_back(curr);
        for(int i = 1;i <= k;i++){
            result[0].push_back(i);
        }
        return result;
    }
    
   
    helper(result,curr,1,n,k);
  
    return result;
    
}


void helper(vector<vector<int>>& res,vector<int>& cur,int start,int n,int k){
    if(cur.size() == k){
        res.push_back(cur);
        return ;
    }
    
    for(int i = start;i <= n ;i++){
        if(find(cur.begin(),cur.end(),i) == cur.end()){
            cur.push_back(i);
            helper(res,cur,i + 1,n,k);
            cur.pop_back();
        }    
    }
}

Given a set of candidate numbers (C) (without duplicates) 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.
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]
]

方法和上面那个很相似

vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    vector<vector<int>> res;
    vector<int> cur;
    helper(res,cur,candidates,target);
    
    return res;
}

void helper(vector<vector<int>>& res,vector<int>& cur,const vector<int>& info,int sum){
    if(sum == 0){
        
        for(int i = 0;i < res.size();i++){
            if(is_permutation(res[i].begin(),res[i].end(),cur.begin())){
                return ;
            }
        }
        res.push_back(cur);
        return ;
    }   
    
    for(int i = 0;i < info.size();i++){
        if(info[i] <= sum){
            cur.push_back(info[i]);
            helper(res,cur,info,sum - info[i]);
            cur.pop_back();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 阅读杜拉拉升职记175页到192页 感悟.杜拉拉升职记是我们HR经理推荐,开始以为是小说,其实不然。职场人士必...
    汩雨猫阅读 2,571评论 0 0
  • 设计模式是什么?设计模式是经过总结、优化的,对我们经常会碰到的一些编程问题的可重用解决方案。一个设计模式并不像一个...
    静熙老师哈哈哈阅读 3,596评论 0 7
  • 【聊•感】 给好友打了两个小时电话。聊聊自己的事情想看他的观点。我很认同。是因为书上这么说。他也这么说。其实我也认...
    言十年阅读 1,293评论 0 0
  • 03 A2:见面,s床。后来她打电话约我见面,我把第一次见面的地点框架到我家里。在没见面以前她就对我很有感觉了,见...
    一条老白狼阅读 3,273评论 0 0