Any way to improve my solution


  • 0
    B
    public String getPermutation(int n, int k) {
    		 List<Integer> remdigits=new ArrayList<Integer>();
    		 for(int i=1;i<=n;i++)
    			 remdigits.add(i);
    		return permute(n, k, remdigits, "");	        
    	    }
    	 public static String permute(int n, int k,List<Integer> remdigits,String answer){
    		 if(remdigits.isEmpty()) {
    			 return answer;
    		 }
    		 if(k==0) {
    			 for(Integer l:remdigits)
    				 answer+=""+l;
    			 return answer;
    		 }
    		 int fact=factorial(n-1);
    		 int i;
    		 for(i=1;i<=n;i++) { //n5 k2
    			 if(k<=i*fact)
    				 break;
    		 }
    		 answer=answer+""+remdigits.get(i-1);
    		 remdigits.remove(i-1); 
    		return permute(n-1, k-(i-1)*fact, remdigits, answer);		 
    	 }
    	 public static int factorial(int n){
    		 if(n==1 || n==0)
    			 return 1;
    		 int sum=1;
    		 while(n>0) {
    			 sum*=n;
    			 n--;
    		 }
    		 return sum;
    	 }`enter code here`

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.