leetcode Combinations题解

博客围绕给定两个整数n和k,从1 - n中选k个数字求不重复组合的问题展开。先给出英文题目描述及中文理解,解题思路是用回溯法,先排除n小于1和k大于n的异常情况,再递归实现,还给出了Java代码。

题目描述:

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

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

中文理解:

给定两个整数n,k,其中n代表数列1-n,k代表k个元素,从1-n中随机选择k个数字,问共有多少种不重复的组合,每个组合中增序。

解题思路:

使用回溯的方法,首先排除异常情况n小于1和k大于n的情况,然后使用回溯的方法递归实现,具体见代码。

代码(java):

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res =new ArrayList();
        if(n<1 || n<k)return res;
        traceback(res,new ArrayList<Integer>(),n,k);
        return res;
    }
    public void traceback(List<List<Integer>> res,ArrayList<Integer> tempList,int n,int k){
        if(tempList.size()==k){
            res.add(new ArrayList(tempList));
            return;
        }
        else{
            //这里通过i的设置,保持序列是递增的,同时筛选掉1,4和4,1这种等价的组合。
            int i=1;
            if(tempList.size()>0)i=tempList.get(tempList.size()-1);
            for(;i<=n;i++){
                if(tempList.contains(i))continue;
                tempList.add(i);
                traceback(res,tempList,n,k);
                tempList.remove(tempList.size()-1);
            }
        }
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值