LeetCode 46. Permutations

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],
  [3,2,1]
]

给出数列列出全部的排列组合,首先想到递归,然后是回溯的思路

比如对于1 , 如果在 2 3的排列组合都求出的情况下

只需将1 与 每一个组合中的每一个数交换一次就是最后的结果了

因此递归函数需要三个参数:条件数组num[],结果lists,当前index

函数功能:在当前index之后的排列完成的情况下加入当前index形成新的组合,删除原先组合

public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        if (nums.length !=0) {
            rPermute(nums,lists,0);
        } 

        return lists;
    }

    public void rPermute(int[]nums,List<List<Integer>> lists, int index) {
        if (index != nums.length - 1) {
            rPermute(nums, lists, index + 1);
        } else {
            List<Integer> firstList = new ArrayList<Integer>();
            firstList.add(nums[index]);
            lists.add(firstList);
            return;
        }
        //保存原先的组合数量
        int listSize = lists.size();
        for (int i = 0 ; i < listSize; i++) {
            List<Integer> list = lists.get(i);
            int size = list.size();
            //在每一个组合中加入新的元素
            for (int j = 0; j <= size; j++) {
                List<Integer> tmpList = new ArrayList<Integer>(list);
                tmpList.add(j, nums[index]);
                lists.add(tmpList);
            }
        }
        //删除原先的组合
        for (int i = 0; i < listSize; i++) {
            lists.remove(0);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值