Print all permutations of the given array.
Example:
Input: arr={1,2,3}
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;public class AllpermutationGivenArray {public static void main(String[] args) {int arr[] = { 1, 2, 3 };ans = new ArrayList<List<Integer>>();permutations(arr, 0, arr.length - 1);System.out.println(Arrays.asList(ans));}static List<List<Integer>> ans;//function to find all the permutaions of the//given stringstatic void permutations(int[] arr, int l, int r) {// base case if l and r same// then push the string into the// vector of stringsif (l == r) {ans.add(Arrays.stream(arr).boxed().collect(Collectors.toList()));} else {for (int i = l; i <= r; i++) {int tmp = arr[l];arr[l] = arr[i];arr[i] = tmp;permutations(arr, l + 1, r);// backtracktmp = arr[l];arr[l] = arr[i];arr[i] = tmp;}}}}
C++
#include <bits/stdc++.h>using namespace std;vector<vector<int>> ans;//function to find all the permutaions of the//given stringvoid permutations(vector<int> arr,int l,int r){//base case if l and r same//then push the string into the//vector of stringsif(l==r){ans.push_back(arr);}else{for(int i=l;i<=r;i++){swap(arr[l],arr[i]);permutations(arr,l+1,r);//backtrackswap(arr[l],arr[i]);}}}int main(){vector<int> arr={1,2,3};ans.clear();permutations(arr,0,arr.size()-1);cout<<"[";for(int i=0;i<ans.size();i++){cout<<"[";for(int j=0;j<ans[i].size();j++){cout<<ans[i][j];if(j!=ans[i].size()-1)cout<<",";}cout<<"]";if(i!=ans.size()-1)cout<<",";}cout<<"]";return 0;}
No comments:
Post a Comment