lintcode-medium-Permutations

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Permutations相关的知识,希望对你有一定的参考价值。

Given a list of numbers, return all possible permutations.

 

Example

For nums = [1,2,3], the permutations are:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
Challenge

Do it without recursion.

 

class Solution {
    /**
     * @param nums: A list of integers.
     * @return: A list of permutations.
     */
    public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {
        // write your code here
        
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        if(nums == null || nums.size() == 0)
            return result;
        
        ArrayList<Integer> line = new ArrayList<Integer>();
        boolean[] visited = new boolean[nums.size()];
        
        helper(result, line, visited, nums);
        
        return result;
    }
    
    public void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> line, boolean[] visited, ArrayList<Integer> nums){
        
        if(line.size() == nums.size()){
            result.add(new ArrayList<Integer>(line));
            return;
        }
        
        for(int i = 0; i < nums.size(); i++){
            if(!visited[i]){
                line.add(nums.get(i));
                visited[i] = true;
                helper(result, line, visited, nums);
                line.remove(line.size() - 1);
                visited[i] = false;
            }
            
        }
        
        return;
    }
    
}

 

以上是关于lintcode-medium-Permutations的主要内容,如果未能解决你的问题,请参考以下文章