Share my java code


  • 0
    Q

    Is there someone have the same idea for this question?

     public String getPermutation(int n, int k) {
    		 ArrayList nums = new ArrayList();
    		 for (int i = 0; i < n; i++) {
    			nums.add(i+1);
    		}
    		 return permute(k,nums,0);
    		}
    
    	private String permute(int k, ArrayList nums,int i) {
    		String rv = "";
    		k = k-1;
    		if(nums.size()==1) return nums.get(0)+"";
    		int index = k/rep(nums.size()-1);
    		int need = (int) nums.get(index);
    		nums.remove(index);
    		k = k%rep(nums.size());
    		return need+""+permute(k+1, nums, i+1);
    	}
    	private int rep(int i){
    		int rv = 1;
    		while(i!=1){
    			rv *=i;
    			i--;
    		}
    		return rv;
    	}
    

Log in to reply
 

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