AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 51. 数字排列    原题链接    中等

作者: 作者的头像   后来_7 ,  2019-09-11 11:01:30 ,  所有人可见 ,  阅读 862


0


1

循环递归,回溯

class Solution {
    List<List<Integer>> res = new LinkedList<List<Integer>>();
    boolean[] used = new boolean[1024];// nums中第i个元素是否使用过,添加到path中

public List<List<Integer>> permutation(int[] nums) {
    res.clear();
    if (nums.length == 0) {
        return res;
    }
    Arrays.sort(nums);
    generatePermutation(nums, 0, new LinkedList<>());
    return res;

}

// path保存了一个有index个元素的排列
// 向这个排列的末尾添加第index+1个元素,获得一个有index+1个元素的排列
private void generatePermutation(int[] nums, int index, List<Integer> path) {
    // boolean[] used = new boolean[nums.length];// nums中第i个元素是否使用过,添加到path中
    if (index == nums.length) {
        res.add(new ArrayList<Integer>(path));
        return;
    }

    // 循环加递归!!就是回溯!!
    for (int i = 0; i < nums.length; i++) {
        if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
            continue;
        }

            path.add(nums[i]);
            used[i] = true;
            // 尝试着将所有剩余没有用过的元素添加到path中去,将所有没有用过的元素,添加到index位置
            // 可以这样理解,在循环中,只有i是变化的,index是不变的,因此就可以看作是将所有的元素遍历一遍,尝试添加到index位置上
            generatePermutation(nums, index + 1, path);
            // 回复状态,添加循环后的另一个元素,将循环遍历的所有元素都尝试添加一遍,回溯
            path.remove(index);
            used[i] = false;

    }
}

}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息