LeetCode_46 Permutations

Link to original problem: 这里写链接内容
Given a collection of distinct 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].

Related problems:
31 Next Permutation: 这里写链接内容
47 Permutations II: 这里写链接内容
60 Permutation Sequence: 这里写链接内容
77 Combinations: 这里写链接内容

英文表达可能有不少问题,所以以后更新还是尽量使用中文QAQ。

本题也是一道非常常规背包问题,这里的排列从1,2,3,…,n。然后是1,2,3,…,n, n-1。依次类推。我们可以讲该问题考虑成一个背包,最终我们是需要讲所有数字都装进这个背包中的,只是装进去的顺序不同而已。

考虑第一次放物体进入背包,我们可以选择从1到n的任意一个数字,并且最先放置1,这个解最终在输出结果的顺序是要先于最先放置2的,而最先放置2的所有解的顺序是要先于所有除1以外的数字的。所以这里我们可以使用一个boolean 数组以标志所有的数字被使用与否,然后在每次的循环中遍历,如果标记为false,则将这个数字装进背包,并进入下一轮背包(recursion)。记得在调用下一轮背包的语句结束之后,拿出这一轮使用的数字即可。下面是具体代码:

public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums == null || nums.length == 0) return res;
        List<Integer> cur = new ArrayList<Integer>();
        boolean[] used = new boolean[nums.length];
        helper(res, cur, nums, used, 0);
        return res;
    }
    private void helper(List<List<Integer>> res, List<Integer> cur, int[] nums, boolean[] used, int count){
        if(count == nums.length){
            res.add(new ArrayList<Integer>(cur));
            return;
        }
        for(int ii = 0; ii < nums.length; ii++){
            if(used[ii] == false){
                cur.add(nums[ii]);
                used[ii] = true;
                helper(res, cur, nums, used, count+1);
                cur.remove(cur.size()-1);
                used[ii] = false;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值