zoukankan      html  css  js  c++  java
  • leetcode : permutation

    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]
    ]

    思路: backtrack
    public class Solution {
        public List<List<Integer>> permute(int[] nums) {
            
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(nums == null || nums.length == 0) {
                return result;
            }
            ArrayList<Integer> list = new ArrayList<Integer>();
            helper(result,list,nums);
            return result;
        }
        
        public void helper(List<List<Integer>> result, ArrayList<Integer> list, int[] nums) {
            
            if(list.size() == nums.length) {
                result.add(new ArrayList<Integer>(list));
            }
            
            for(int i = 0; i < nums.length; i++) {
                if(list.contains(nums[i])) {
                    continue;
                }
                list.add(nums[i]);
                helper(result,list,nums);
                list.remove(list.size() - 1);
            }
        } 
    }
    
  • 相关阅读:
    怎么在myeclipse中怎么集成Tomcat。
    JSP .基础概念
    继承
    封装
    什么是面向对象
    数据排序
    开发的套路
    Javabean规范
    转发和重定向
    md5加密
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6394075.html
Copyright © 2011-2022 走看看