组合-lintcode

这是回溯类型的简单题。
分析:
- 函数一定要传一个引用类型的vector,以便以后可以往里加数据。其他参数包括n,k,temp(这个就不可以是引用了),还有最重要的一个i,这个函数栈里应该从哪取。
- 函数里首先应该判断return的条件,即result.size()==k或者temp的最后一个元素达到最大n时return。接下来是for循环,每次重新分配一个temp2,然后往里加i,再调用函数,这样可以从小到大找完所有的可能。
C++代码:

class Solution {
public:
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int>> result;
        vector<int> temp;
        if (0==n || 0==k){
            return result;
        }
        process(result,temp,n,k,1);
        return result;
    }
    void process(vector<vector<int>>&result, vector<int> temp, int n, int k,int i) {
        if (temp.size() == k) {
            result.push_back(temp);
            return;
        }
        if (temp.size()>=1 && temp[temp.size()-1] == n) {
            return;
        }

        for ( ; i<=n; i++) {
            vector<int> temp2 = temp;
            temp2.push_back(i);
            process(result,temp2,n,k,i+1);
        }
    }
};

然后我又看了网友的代码,对每个元素,取或不取,递归调用。
他的代码:

class Solution {  
public:  
    /** 
     * @param n: Given the range of numbers 
     * @param k: Given the numbers of combinations 
     * @return: All the combinations of k numbers out of 1..n 
     */  
    vector<vector<int> > combine(int n, int k) {  
        // write your code here  
        vector<vector<int> > ret;  
        vector<int> cur;  
        combine(cur,1,n,k,ret);  
        return ret;  
    }  
    void combine(vector<int> cur,int index,int n,int k,vector<vector<int> >&ret)  
    {  
        if(cur.size()==k)  
        {  
            ret.push_back(cur);  
            return;  
        }  
        if(index>n||cur.size()>k)  
            return;  
        combine(cur,index+1,n,k,ret);  
        cur.push_back(index);  
        combine(cur,index+1,n,k,ret);  
    }  

}; 

最后三行加他的解释简直道出了回溯的本质,第一行表示不取index,第二行取该元素index,地三行表示取该元素index。
总结:
发现别人的思想总能给你启发,要多多发现并吸收;另外,感觉回溯法用于解决那些组合类型的问题,就是看看哪些组合是满足要求的,然后递归求解,八皇后问题也是如此。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值