Permutations

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]
]
solution:
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        for(int i = 0; i< nums.length; i++){
            if(i == 0) {ans.add(Arrays.asList(nums[i]));continue;} 
            List<List<Integer>> temp = new ArrayList<>();
            for(List<Integer> l : ans){
                List<Integer> it = new ArrayList<Integer>(l);
                for(int j  = 0; j <= i; j++){
                    it = new ArrayList<Integer>(l);
                    it.add(j,nums[i]);
                    temp.add(it);
                }
            }
            ans = temp;
        }
        return ans;
    }

}

results matching ""

    No results matching ""