Print all the permutations of the given string
Example:
Input: str="ABC"
Output: {"ABC","ACB","BAC","BCA","CBA","CAB"}
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class AllpermutationGivenString {public static void main(String[] args) {String str = "ABC";ans = new ArrayList<String>();char ch[] = str.toCharArray();permutations(ch, 0, str.length() - 1);System.out.println(Arrays.asList(ans));}static List<String> ans;// function to find all the permutaions of the// given stringstatic void permutations(char[] ch, int l, int r) {// base case if l and r same// then push the string into the// vector of stringsif (l == r) {ans.add(new String(ch));} else {for (int i = l; i <= r; i++) {char tmp = ch[l];ch[l] = ch[i];ch[i] = tmp;permutations(ch, l + 1, r);tmp = ch[l];ch[l] = ch[i];ch[i] = tmp;}}}}
C++
#include <bits/stdc++.h>using namespace std;vector<string> ans;//function to find all the permutaions of the//given stringvoid permutations(string str,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(str);}else{for(int i=l;i<=r;i++){swap(str[l],str[i]);permutations(str,l+1,r);swap(str[l],str[i]);}}}int main(){string str="ABC";ans.clear();permutations(str,0,str.size()-1);for(int i=0;i<ans.size();i++)cout<<ans[i]<<" ";return 0;}
No comments:
Post a Comment