leetcode 77. Combinations-排列|递归|非递归|Java|Python

原题链接:77. Combinations

【思路-Java、Python】递归实现

采用回溯算法。这是一道 NP 难问题,时间复杂度没办法提高,用一个循环递归处理子问题,问题的终止条件是每个组合中的元素个数达到 k 个:

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        dfs(res, temp, n, k, 1);
        return res;
    }
    private void dfs(List<List<Integer>> res, List<Integer> temp, int n, int k, int m) {
        if(k == 0) {
            res.add(new ArrayList<Integer>(temp));
            return;
        }
        for(int i=m; i<=n; i++) {
            temp.add(i);
            dfs(res, temp, n, k-1, i+1);
            temp.remove(temp.size()-1);
        }
    }
}
26 / 26  test cases passed. Runtime: 3 ms  Your runtime beats 56.70% of javasubmissions.

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        res = []
        self.rec(res, 0, n, k, [])
        return res
    def rec(self, res, i, n, k, temp) :
        if k == 0 :
            res.append(temp)
            return
        for j in range(i+1, n+1) :
            self.rec(res, j, n, k-1, temp+[j])
26 / 26  test cases passed. Runtime: 88 ms  Your runtime beats 32.21% of pythonsubmissions.


【思路2-Python】非递归实现

class Solution(object):
    def combine(self, NN, K):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        result = [[[]]]
        for n in range(1,NN+1):
            newRes=[[[]]]
            for k in range(1,n):
                newRes.append(result[k] + [i + [n] for i in result[k-1]])
            newRes.append([result[n-1][0] + [n]])
            result = newRes
        return result[K]
26 / 26  test cases passed. Runtime: 88 ms  Your runtime beats 32.21% of pythonsubmissions.

更优解法可参考:优化解法
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值