[LeetCode][CH1-1]Permutations

Problem:

Given a collection of numbers, return all possible permutations.


For example,

[1,2,3] have the following permutations:


[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].


Solution:


套用Subsets的模版,此处与Subsets不同的地方是只有当当前的path中的元素个数=num的元素个数的时候,才将path加入到result中(代码红色标注的地方)。此外,由于生成排列的序列时需要检查某元素是否已经在当前的path中,使用了一个visited数组。由于题目默认given collection中没有重复元素,所以另一种方法是直接用path.contans(num[i])来检查。


public class Solution {//test cases:
    //[]
    //null
    //[1,2,3]
    //[1]
    //[1,2,..,100]
    //[1,2,2] -- 不需要考虑
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (num == null || num.length == 0) {
            return result;
        }
        permuteHelper(num, new ArrayList<Integer>(), result, new boolean[num.length]);
        return result;
    }
    
    private void permuteHelper(int[] num, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> result, boolean[] selected) {
        if (path.size() == num.length) {
            result.add(new ArrayList<Integer>(path));
            return;
        }
        
        for (int i = 0; i < num.length; i++) {
            if (selected[i] == true) {//或者path.contains(num[i]) == true
                continue;
            }
            path.add(num[i]);
            selected[i] = true;
            permuteHelper(num, path, result, selected);
            selected[i] = false;
            path.remove(path.size() - 1);
        }
     }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值