leetcode77.组合Java

LeetCode.77 组合

在这里插入图片描述

解法一:DFS+回溯法

图解:
在这里插入图片描述

代码:

package com.leetcode.solution;

import java.util.*;

/**
 * @Author : fanc
 * @Date : 2019-09-01 19:25
 */
public class Solution77 {
    List<List<Integer>> output = new LinkedList<>();
    int n;
    int k;

    public void traceback(int first, LinkedList<Integer> current) {
        if (current.size() == k) {
            //错误,不能直接加上current,否则所有的元素都是一个引用
            //output.add(current);
            output.add(new LinkedList<Integer>(current));
            System.out.println(output);
            return;
        }

        for (int i = first; i <= n; i ++) {
            //保存回溯结果
            //LinkedList<Integer> temp = new LinkedList<>(current);
            current.add(i);
            traceback(i + 1, current);
            //回溯:第一种方法current.removeLast()因为每一个add后面跟一个remove保证回溯
            //current = temp;
            current.removeLast();
        }
    }

    public List<List<Integer>> combine(int n, int k) {
        this.n = n;
        this.k = k;
        traceback(1, new LinkedList<>());
        return output;
    }
}

有两种回溯方法:

  1. 保存current结果
  2. add之后然后remove,保证一对一

需要注意的是,需要每次new一个list,防止每一个引用都一样,也就是需要有一个深拷贝的过程

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值