LeetCode Permutations

来源:互联网 发布:java websocket 跨域 编辑:程序博客网 时间:2024/06/06 08:47

Description:

Given a collection of numbers, return all possible permutations.

Solution:

I remember this is the most basic algorithm on the book Data Structure.

import java.util.ArrayList;import java.util.List;public class Solution {List<List<Integer>> list;public List<List<Integer>> permute(int[] nums) {list = new ArrayList<List<Integer>>();dfs(0, nums);return list;}void dfs(int tot, int nums[]) {if (tot == nums.length) {ArrayList<Integer> l = new ArrayList<Integer>();for (int i = 0; i < nums.length; i++)l.add(nums[i]);System.out.println(l);list.add(l);return;}int temp;for (int i = tot; i < nums.length; i++) {temp = nums[tot];nums[tot] = nums[i];nums[i] = temp;dfs(tot + 1, nums);temp = nums[tot];nums[tot] = nums[i];nums[i] = temp;}}public static void main(String[] args) {Solution s = new Solution();s.permute(new int[] { 1, 2, 3, 4 });}}



0 0