LintCode-----15.全排列

原题目

1.自己

就是使用深搜.深搜很多用处,包括后面的什么子数组最大和等等。
1047ms


import java.util.ArrayList;
import java.util.List;

public class Solution {

    public List<List<Integer>> permute(int[] nums) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> item = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            result.add(item);
            return result;
        }
        int[] book = new int[nums.length];
        dfs(nums, book, 0, item, result);
        return result;

    }

    public void dfs(int[] nums, int[] book, int step, List<Integer> item, List<List<Integer>> result) {
        if (step == book.length) {
            result.add(new ArrayList<>(item));
            return;
        }
        for (int i = 0; i < book.length; i++) {
            if (book[i] == 0) {
                book[i] = 1;
                item.add(nums[i]);
                dfs(nums, book, step + 1, item, result);
                item.remove(item.size() - 1);
                book[i] = 0;
            }
        }
    }

    public void print(List<List<Integer>> result) {
        for (List<Integer> list : result) {
            for (Integer i : list) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = new int[]{2, 1};
        List<List<Integer>> result = solution.permute(nums);
        solution.print(result);
    }

}

2.九章

居然是2409ms.难道是?好像是说的使用contain比较耗时。

使用了list的contain方法就没有使用标记数组,还是比较方便


public class Solution {
    public List<List<Integer>> permute(int[] nums) {
         ArrayList<List<Integer>> rst = new ArrayList<List<Integer>>();
         if (nums == null) {
             return rst; 
         }

         if (nums.length == 0) {
            rst.add(new ArrayList<Integer>());
            return rst;
         }

         ArrayList<Integer> list = new ArrayList<Integer>();
         helper(rst, list, nums);
         return rst;
    }

    public void helper(ArrayList<List<Integer>> rst, ArrayList<Integer> list, int[] nums){
        if(list.size() == nums.length) {
            rst.add(new ArrayList<Integer>(list));
            return;
        }

        for(int i = 0; i < nums.length; i++){
            if(list.contains(nums[i])){
                continue;
            }
            list.add(nums[i]);
            helper(rst, list, nums);
            list.remove(list.size() - 1);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值