码迷,mamicode.com
首页 > 其他好文 > 详细

Permutations

时间:2015-06-18 08:15:07      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

Given a collection of 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].

递归,每次向两个元素间插入新元素。

public class Solution {
  public List<List<Integer>> permute(int[] nums) {
    return helper(nums, 0);
  }

  public List<List<Integer>> helper(int[] nums, int offset) {
    if (offset == nums.length) {
      List<List<Integer>> result = new ArrayList<>();
      result.add(new ArrayList<>());
      return result;
    }
    List<List<Integer>> result = helper(nums, offset + 1);
    List<List<Integer>> newResult = new ArrayList<>();
    for (List<Integer> list : result) {
      for (int i = 0; i < list.size() + 1; i++) {
        List<Integer> newList = new ArrayList<>(list);
        newList.add(i, nums[offset]);
        newResult.add(newList);
      }
    }
    return newResult;
  }
}

Permutations

标签:

原文地址:http://www.cnblogs.com/shini/p/4584851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!