|
| 1 | +//LeetCode 46. Permutation |
| 2 | +//Question - https://leetcode.com/problems/permutations/ |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public List<List<Integer>> permute(int[] nums) { |
| 6 | + List<List<Integer>> res = new ArrayList<>(); |
| 7 | + boolean visit[] = new boolean[nums.length]; |
| 8 | + |
| 9 | + helper(nums, visit, new ArrayList<>(), res); |
| 10 | + return res; |
| 11 | + } |
| 12 | + |
| 13 | + public void helper(int nums[], boolean visit[], List<Integer> perm, List<List<Integer>> res){ |
| 14 | + //Base Case |
| 15 | + if(perm.size() == nums.length){ |
| 16 | + res.add(new ArrayList<>(perm)); |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + for(int i = 0 ; i < nums.length ; i++){ |
| 21 | + //Check if nums[i] is already in the current permutation or not |
| 22 | + if(visit[i]) continue; |
| 23 | + |
| 24 | + //mark nums[i] as visited for the current permutation |
| 25 | + visit[i] = true; |
| 26 | + perm.add(nums[i]); |
| 27 | + |
| 28 | + //generate the permutation further |
| 29 | + helper(nums, visit, perm, res); |
| 30 | + |
| 31 | + //backtrack to generate new permutation |
| 32 | + visit[i] = false; |
| 33 | + perm.remove(perm.size()-1); |
| 34 | + } |
| 35 | + } |
| 36 | +} |
0 commit comments