29-回溯算法-491.递增子序列 46.全排列 47.全排列2

491.递增子序列

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
还没有调对代码,首先占位置。

在这里插入代码片

46.全排列

给定一个 没有重复 数字的序列,返回其所有可能的全排列。
输入: [1,2,3]
输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

思路:因为需要改变顺序,所以不需要start了,同时维护一个used数组来保存是否使用过,当path中的值与数组长度相等的时候存储并return就行。
注意:要对used数组进行初始化!

class Solution {
    List<List<Integer>> list = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;
    public List<List<Integer>> permute(int[] nums) {
        used = new boolean[nums.length];
        permute1(nums);
        return list;
    }
    public void permute1(int[] nums){
        if(path.size() == nums.length){
            list.add(new ArrayList(path));
            return;
        }
        for(int i = 0; i < nums.length; i ++){
            if(used[i] == false){
                path.add(nums[i]);
                used[i] = true;
            }else{
                continue;
            }
            permute1(nums);
            path.removeLast();
            used[i] = false;
        }
    }
}

47.全排列2

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
输入:nums = [1,1,2]
输出: [[1,1,2], [1,2,1], [2,1,1]]

思路:和上一个问题相比,提供的数组中可以包含重复数字,采用used数组同时也要思考怎么去除重复。首先对数组进行排序,然后增加去重操作。如果这个位置的数字和前一个位置的数字相等,并且前一个used为假,则这一次跳过。

class Solution {
    List<List<Integer>> list = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    boolean[] used;
    public List<List<Integer>> permuteUnique(int[] nums) {
        used = new boolean[nums.length];
        Arrays.sort(nums);
        permute1(nums);
        return list;
    }
    public void permute1(int[] nums){
        if(path.size() == nums.length){
            list.add(new ArrayList(path));
            return;
        }
        for(int i = 0; i < nums.length; i ++){
            if(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false){
                continue;
            }
            if(used[i] == false){
                path.add(nums[i]);
                used[i] = true;
            }else{
                continue;
            }
            permute1(nums);
            path.removeLast();
            used[i] = false;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值